Django的新手,并坚持这个错误。我的模板正确呈现。我做的唯一改变是增加一个' 1/0'在我的views.py文件中模拟断点。现在,当我删除它时,模板将不会呈现。
urls.py
from django.conf.urls import url
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.views import login, logout
from app.views import send_morsel, start_hunt, MorselList, MorselDetailView,\
register, create_morsel, HomePageView, FAQPageView, AboutPageView,\
newsletter_signup, edit_morsel
app_name = 'app'
urlpatterns = [
url(r'^$', HomePageView.as_view(), name='home'),
url(r'^morsels/$', MorselList.as_view(), name='morsel_list'),
url(r'^morsels/send/$', send_morsel, name='morsel_send'),
url(r'^morsels/(?P<morsel_id>[0-9])/start_hunt/$', start_hunt, name='start_hunt'),
url(r'^register/', register, name='register'),
url(r'^faq/$', FAQPageView.as_view(), name='faq'),
url(r'^about/$', AboutPageView.as_view(), name='about'),
url(r'^morsels/create/$', create_morsel, name="create_morsel"),
url(r'^morsels/(?P<morsel_id>[0-9])/edit/$', edit_morsel, name='edit_morsel'),
url(r'^morsels/(?P<pk>[0-9])/display/$', MorselDetailView.as_view(), name='morsel_detail'),
url(r'^newsletter_signup/$', newsletter_signup, name='newsletter_signup')
]
morsel_list.html
{% extends "app/base.html" %}
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% bootstrap_messages %}
{% block content %}
<h2>Morsels</h2>
{% if user.is_authenticated %}
<p>hello</p>
<p>welcome {{ user.username }}</p>
<p><a href="/logout">Logout</a></p>
{% else %}
<p><a href="/login">Login</a></p>
<p><a href="/app/register">Register</a></p>
{% endif %}
<ul>
{% for morsel in object_list %}
<li>{{ morsel.name }}
<a href="{%url 'app:morsel_detail' morsel.id%}">View</a>
<a href="{%url 'app:edit_morsel' morsel.id %}">Edit</a>
<a href="{%url 'app:start_hunt' morsel.id%}">Send! </a>
</li>
{% endfor %}
</ul>
{% if messages %}
{% for msg in messages %}
{% bootstrap_alert msg.message alert_type=msg.level_tag %}
{% endfor %}
{% endif %}
{% endblock %}
真的不知道该怎么办。
来自views.py的相关块:
def edit_morsel(request, morsel_id=None):
if request.method == 'POST':
extra = int(request.session['extra'])
form = MorselCreationForm(request.POST)
formset = formset_factory(QuestionAnswerCreationForm, extra=extra)(request.POST)
if form.is_valid() and formset.is_valid():
name = form.cleaned_data["name"]
start_time = form.cleaned_data["start_time"]
end_time = form.cleaned_data["end_time"]
welcome_text = form.cleaned_data["welcome_text"]
completed_text = form.cleaned_data["completed_text"]
public_enabled = form.cleaned_data["public_enabled"]
m = Morsel(
name=name,
start_time = start_time,
end_time = end_time,
welcome_text = welcome_text,
completed_text = completed_text,
public_enabled = public_enabled
)
m.save()
# this order is important to be able to access the relations
for form in formset:
question_text = form.cleaned_data["question_text"]
q = Question(
question_text=question_text,
morsel = m
)
answer = Answer(question=q)
q.answer.answer_text = form.cleaned_data["answer_text"]
q.save()
morsel = get_object_or_404(Morsel.objects.prefetch_related('questions'), pk=morsel_id)
form = MorselCreationForm(initial={
"start_time" : morsel.start_time,
"end_time" : morsel.end_time,
"name" : morsel.name,
"welcome_text" : morsel.welcome_text,
"completed_text" : morsel.completed_text,
"public_enabled" : morsel.public_enabled
})
initial_formset_values = [{"question_text":question.question_text,"answer_text":question.answer.answer_text} \
for question in morsel.questions.select_related("answer").all()]
formset = formset_factory(QuestionAnswerCreationForm, extra=1, max_num=len(morsel.questions.all()))(initial=initial_formset_values)
return render(request, 'app/edit_morsel.html', {'form':form, 'formset':formset})
回溯:
Environment:
Request Method: GET
Request URL: http://localhost:8000/app/morsels/
Django Version: 1.11.6
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app.apps.AppConfig',
'django_extensions',
'twilio',
'debug_toolbar',
'bootstrap3',
'sass_processor']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Template error:
In template /Users/kiniadit/code/morsels/app/templates/app/base.html, error at line 12
Reverse for 'morsel_detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['app/morsels/(?P<pk>[0-9])/display/$'] 2 : <html><head>
3 : <meta charset="utf-8">
4 : <meta name="viewport" content="width=device-width, initial-scale=1">
5 : <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">s
6 :
7 : <!-- Custom links -->
8 : <link href="{% static 'app/css/style.css' %}" rel="stylesheet" type="text/css" />
9 : <body>
10 : <nav class="navbar navbar-expand-md navbar-dark bg-success">
11 : <div class="container">
12 : <a class="navbar-brand" href="/"><img sr c="{% static 'app/images/logo.png' %}"></a>
13 : <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbar2SupportedContent" aria-controls="navbar2SupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button>
14 : <div class="collapse navbar-collapse text-center justify-content-end" id="navbar2SupportedContent">
15 : <ul class="navbar-nav">
16 : <li class="nav-item">
17 : <a class="nav-link text-white" href="{% url 'app:about' %}">About</a>
18 : </li>
19 : <li class="nav-item">
20 : <a class="nav-link text-white" href="{% url 'app:faq' %}">FAQ</a>
21 : </li>
22 : </ul>
Traceback:
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
217. response = self.process_exception_by_middleware(e, request)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
215. response = response.render()
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/response.py" in render
107. self.content = self.rendered_content
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/response.py" in rendered_content
84. content = template.render(context, self._request)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/backends/django.py" in render
66. return self.template.render(context)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
207. return self._render(context)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
107. return self.nodelist.render(context)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/loader_tags.py" in render
177. return compiled_parent._render(context)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
107. return self.nodelist.render(context)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/loader_tags.py" in render
72. result = block.nodelist.render(context)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/defaulttags.py" in render
216. nodelist.append(node.render_annotated(context))
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/defaulttags.py" in render
458. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/urls/base.py" in reverse
91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
497. raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /app/morsels/
Exception Value: Reverse for 'morsel_detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['app/morsels/(?P<pk>[0-9])/display/$']
答案 0 :(得分:1)
您的正则表达式与单个数字匹配,因此适用于pk=9
但不适用于pk=10
。添加+
以匹配多个数字。
url(r'^morsels/(?P<pk>[0-9]+)/display/$', MorselDetailView.as_view(), name='morsel_detail'),
您还需要修复使用[0-9]
的其他网址格式。
答案 1 :(得分:0)
在你的urls.py中,你有:url(r'^ morsels /(?P [0-9])/ display / $',MorselDetailView.as_view(),name ='morsel_detail'),pk(primary key)表示您在发出请求时必须命名参数pk。因此,当错误显示时,您尝试发送一个名为morsel.id的参数,假设它是pk,因此它会引发错误,所以在你的morsel_list.html文件中,切换View to View,希望这对你有帮助。