未找到带有参数“(”,)”的“详细信息”的反向。尝试了 1 种模式:['users/(?P<username>[^/]+)/$']
Posted
技术标签:
【中文标题】未找到带有参数“(”,)”的“详细信息”的反向。尝试了 1 种模式:[\'users/(?P<username>[^/]+)/$\']【英文标题】:Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['users/(?P<username>[^/]+)/$']未找到带有参数“(”,)”的“详细信息”的反向。尝试了 1 种模式:['users/(?P<username>[^/]+)/$'] 【发布时间】:2020-10-07 22:09:46 【问题描述】:我正在尝试显示“属性”模型的详细视图。我有点困惑,所以我不知道如何描述这种情况,我以前从未遇到过。
modeles.py
import arrow
from django.db import models
from datetime import datetime
from autoslug import AutoSlugField
from model_utils.models import TimeStampedModel
from django.urls import reverse
from django.conf import settings
class Property(TimeStampedModel):
title = models.CharField(max_length=2000, null=True)
# Localizare
residence_complex = models.CharField(max_length=200, null=True)
state = models.CharField(max_length=200, null=True)
city = models.CharField(max_length=200, null=True)
address = models.CharField(max_length=200, null=True)
street_number = models.IntegerField()
zipcode = models.CharField(max_length=200, null=True)
building = models.CharField(max_length=200, null=True)
entrance = models.CharField(max_length=200, null=True)
apartament = models.CharField(max_length=200, null=True)
reper = models.CharField(max_length=200, null=True)
vecinatati = models.CharField(max_length=200, null=True)
slug = AutoSlugField("Property Address",
unique=True,
always_update=False,
populate_from="title",
null=True)
# Caracteristici
class Destination(models.TextChoices):
BIROURI = "birouri", "Birouri"
REZIDENTIAL = "rezidentaial", "Rezidential"
COMERCIAL = "comercial", "Comercial"
destination = models.CharField("Destination", max_length=20,
choices=Destination.choices, default=Destination.REZIDENTIAL)
class Layout(models.TextChoices):
DECOMANDAT = "decomandat", "Decomandat"
SEMIDECOMANDAT = "semidecomandat", "Semidecomandat"
NEDECOMANDAT = "nedecomandat", "Nedecomandat"
CIRCULAR = "circular", "Circular"
VAGON = "vagon", "Vagon"
layout = models.CharField("Layout", max_length=20,
choices=Layout.choices, default=Layout.DECOMANDAT)
floor = models.DecimalField(max_digits=10, decimal_places=1, null=True)
class ComfortType(models.TextChoices):
UNU = "1", "1"
DOI = "2", "2"
TREI = "3", "3"
LUX = "lux", "Lux"
comfort_type = models.CharField("Comfort Type", max_length=20,
choices=ComfortType.choices, default=ComfortType.UNU)
class InteriorState(models.TextChoices):
OTHER = "other", "Other"
NECESITA_RENOVARE = "necesita-renovare", "Necesita-Renovare"
RENOVAT = "renovat", "Renovat"
NOU = "nou", "Nou"
CARAMIDA = "caramida", "Caramida"
interior_state = models.CharField("Interior State", max_length=20,
choices=InteriorState.choices, default=InteriorState.OTHER)
building_age = models.IntegerField()
usable_sqm = models.DecimalField(max_digits=10, decimal_places=1, null=True)
build_sqm = models.DecimalField(max_digits=10, decimal_places=1, null=True)
# Incaperi si Anexe
rooms = models.IntegerField(null=True)
bedrooms = models.IntegerField(null=True)
kitchen = models.IntegerField(null=True)
bathrooms = models.IntegerField(null=True)
balcony = models.BooleanField(default=False)
garage = models.BooleanField(default=False)
# Caracteristici Imobil
class BuildingType(models.TextChoices):
BETON = "beton", "Beton"
CARAMIDA = "caramida", "Caramida"
LEMN = "lemn", "Lemn"
BCA = "bca", "Bca"
METAL = "metal", "Metal"
OTHER = "other", "Other"
building_type = models.CharField("Building Type", max_length=20,
choices=BuildingType.choices, default=BuildingType.BETON)
construction_date = models.DateTimeField(null=True, blank=True)
class ConstructionType(models.TextChoices):
HOUSE = "house", "House"
MIXT_BUILDING = "mix-building", "Mix-Building"
STUDIO_BUILDING = "studio-building", "Studio-Building"
construction_type = models.CharField("Construction Type", max_length=20,
choices=ConstructionType.choices, default=ConstructionType.MIXT_BUILDING)
basement = models.BooleanField(default=True)
notes = models.TextField(blank=True)
lot_size = models.DecimalField(max_digits=10, decimal_places=1)
# Dotari si Utilitati
# Pret
buy_price = models.DecimalField(max_digits=10, decimal_places=1, null=True)
sell_price = models.DecimalField(max_digits=10, decimal_places=1, null=True)
rent = models.DecimalField(max_digits=10, decimal_places=1, null=True)
# Poze
photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_7 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_8 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_9 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_10 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_11 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_12 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
description = models.TextField(blank=True)
# Listing Details
is_published = models.BooleanField(default=True)
list_date = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
""""Return absolute URL to the Contact Detail page."""
return reverse('properties:detail', kwargs="slug": self.slug)
@ property
def created_on_arrow(self):
return arrow.get(self.created_on).humanize()
@property
def photoMain(self):
try:
url = self.photo_main.url
except:
url = ''
return url
urls.py
from django.urls import path, include
from . import views
from django.conf.urls.static import static
from django.conf import settings
app_name = "properties"
urlpatterns = [
# URL Pattern for the PropertyListView
path(
route='',
view=views.PropertyListView.as_view(),
name='list'
),
# URL Pattern for the PropertyCreateView
path(
route='add/',
view=views.PropertyCreateView.as_view(),
name='add'
),
# URL Pattern for the PropertyUpdateView
path(
route='<slug:slug>/update/',
view=views.PropertyUpdateView.as_view(),
name='update'
),
# URL Pattern for the PropertyDetailView
path(
route='<slug:slug>/',
view=views.PropertyDetailView.as_view(),
name='detail'
),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
from .models import Property
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView
)
class PropertyListView(ListView):
model = Property
class PropertyDetailView(DetailView):
model = Property
class PropertyCreateView(LoginRequiredMixin, CreateView):
model = Property
fields = [
'title',
'residence_complex',
'state',
'city',
'address',
'street_number',
'zipcode',
'building',
'entrance',
'apartament',
'reper',
'vecinatati',
'destination',
'layout',
'floor',
'comfort_type',
'interior_state',
'building_age',
'usable_sqm',
'build_sqm',
'rooms',
'bedrooms',
'kitchen',
'bathrooms',
'balcony',
'garage',
'building_type',
'construction_type',
'basement',
'notes',
'lot_size',
'buy_price',
'sell_price',
'rent',
'photo_main',
'photo_1',
'photo_2',
'photo_3',
'photo_4',
'photo_5',
'photo_6',
'photo_7',
'photo_8',
'photo_9',
'photo_10',
'photo_11',
'photo_12',
'description',
'is_published',
'list_date']
def form_valid(self, form):
form.instance.creator = self.request.user
return super().form_valid(form)
class PropertyUpdateView(LoginRequiredMixin, UpdateView):
model = Property
fields = [
'title',
'residence_complex',
'state',
'city',
'address',
'street_number',
'zipcode',
'building',
'entrance',
'apartment',
'reper',
'vecinatati',
'destination',
'layout',
'floor',
'comfort_type',
'interior_state',
'building_age',
'building_sqm',
'usable_sqm',
'build_sqm',
'rooms',
'bedrooms',
'kitchen',
'bathrooms',
'balcony',
'garage',
'building_type',
'construction_type',
'basement',
'notes',
'lot_size',
'buy_price',
'sell_price',
'rent',
'photo_main',
'photo_1',
'photo_2',
'photo_3',
'photo_4',
'photo_5',
'photo_6',
'photo_7',
'photo_8',
'photo_9',
'photo_10',
'photo_11',
'photo_12',
'description',
'is_published',
'list_date'
]
action = "Update"
% extends "base.html" %
% block title %Property List% endblock title %
% block content %
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Widgets</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="#">Home</a></li>
<li class="breadcrumb-item active">Widgets</li>
</ol>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
<section class="content">
<div class="card card-solid">
<div class="card-body pb-0">
<div class="row d-flex align-items-stretch">
% for property in property_list %
<div class="col-12 col-sm-6 col-md-4 d-flex align-items-stretch">
<div class="card bg-light">
<div class="card-header text-muted border-bottom-0">
property.title
</div>
<div class="card-body pt-0">
<div class="row">
<div class="col-7">
<h2 class="lead"><b> property.address property.street_number </b></h2>
<p class="text-muted text-sm"><b>No. Rooms: </b> property.rooms </p>
<p class="text-muted text-sm"><b>Rent Price: </b> property.rent </p>
<p class="text-muted text-sm"><b>Listing Date: </b> property.list_date </p>
</div>
<div class="col-5 text-center">
<img src=" property.photoMain " class="img img-fluid">
</div>
</div>
</div>
<div class="card-footer">
<div class="text-right">
<a href="#" class="btn btn-sm bg-teal">
<i class="fas fa-comments"></i>
</a>
<a href="% url 'properties:detail' property.slug %"
class="btn btn-sm btn-primary">
<i class="fas fa-user"></i> View Details
</a>
</div>
</div>
</div>
</div>
% endfor %
</div>
<hr />
<p>Don't see a contact listed here?</p>
<p>
<a class="btn btn-primary" href="% url 'properties:add' %" role="button">
Add Property
</a>
</p>
</div>
</div>
</section>
</div>
% endblock content %
这很有趣,因为我为另一个应用程序做了完全相同的事情,基本上只是复制和粘贴所有内容,只是稍微更改了模型。但这一个不想工作。
这是我收到的错误消息。
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/properties/piata-romana-3/
Django Version: 3.0.7
Python Version: 3.8.2
Installed Applications:
['whitenoise.runserver_nostatic',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.forms',
'crispy_forms',
'allauth',
'allauth.account',
'allauth.socialaccount',
'django_countries',
'admin_timeline',
'protocol.users.apps.UsersConfig',
'protocol.contacts.apps.ContactsConfig',
'protocol.properties.apps.PropertiesConfig',
'protocol.leads.apps.LeadsConfig',
'debug_toolbar',
'django_extensions']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.common.BrokenLinkEmailsMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Template error:
In template /home/radu/Documents/LESSON/everycheese/protocol/protocol/templates/base.html, error at line 76
Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['users/(?P<username>[^/]+)/$']
66 : <div class="image">
67 : <img src="../../dist/img/user2-160x160.jpg" class="img-circle elevation-2" >
68 : </div>
69 : <div class="info">
70 : <a href="#" class="d-block">Alexander Pierce</a>
71 : </div>
72 : </div>
73 :
74 : <!-- Sidebar Menu -->
75 : <nav class="mt-2">
76 : <ul class="nav nav-pills nav-sidebar flex-co lumn" data-widget="treeview" role="menu" data-accordion="false">
77 : <!-- Add icons to the links using the .nav-icon class
78 : with font-awesome or any other icon font library -->
79 : <li class="nav-item has-treeview">
80 : <a href="#" class="nav-link">
81 : <i class="nav-icon fas fa-tachometer-alt"></i>
82 : <p>
83 : Dashboard
84 : <i class="right fas fa-angle-left"></i>
85 : </p>
86 : </a>
Traceback (most recent call last):
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response
response = response.render()
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/template/response.py", line 105, in render
self.content = self.rendered_content
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content
return template.render(context, self._request)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/template/base.py", line 171, in render
return self._render(context)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render
return self.nodelist.render(context)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/template/base.py", line 936, in render
bit = node.render_annotated(context)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated
return self.render(context)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/template/loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render
return self.nodelist.render(context)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/template/base.py", line 936, in render
bit = node.render_annotated(context)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated
return self.render(context)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/template/loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/template/base.py", line 936, in render
bit = node.render_annotated(context)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated
return self.render(context)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/template/defaulttags.py", line 443, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/urls/base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/home/radu/Documents/LESSON/everycheese/env/lib/python3.8/site-packages/django/urls/resolvers.py", line 677, in _reverse_with_prefix
raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /properties/piata-romana-3/
Exception Value: Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['users/(?P<username>[^/]+)/$']
我很想了解这里发生了什么。我是 Django 新手,显然学习曲线比预期的要难得多。
【问题讨论】:
【参考方案1】:在您的网址中尝试将<slug:slug>
更改为<str:slug>
【讨论】:
【参考方案2】:尝试类似:
<a href="% url 'properties:detail' slug=property.slug %"> Edit </a>
【讨论】:
以上是关于未找到带有参数“(”,)”的“详细信息”的反向。尝试了 1 种模式:['users/(?P<username>[^/]+)/$']的主要内容,如果未能解决你的问题,请参考以下文章
未找到带有参数 '('',)' 的 'todo-user' 的反向操作。已尝试 1 种模式
未找到带有参数“()”和关键字参数“”的“password_change_done”的反向