我的应用已坏了。我正在关注一个教程,我可以创建帖子。但是当我尝试编辑它们时,我收到以下错误
NoReverseMatch at /posts/16/edit/
Reverse for 'detail' with arguments '('1', '6')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['posts/(?P<id>\\d+)/$']
如果我尝试编辑几天前创建的旧帖子,我不会收到此错误。我不知道自己在完成本教程之后做了什么来打破它
继承人我的urls.py
from django.conf.urls import url
from .views import *
urlpatterns = [
url(r'^$', post_list, name='list'),
url(r'^create$', post_create, name='create'),
url(r'^(?P<id>\d+)/$', post_detail, name='detail'),
url(r'^(?P<id>\d+)/edit/$', post_update, name='update'),
url(r'^(?P<id>\d+)/delete/$', post_delete, name='delete'),
]
继承人的观点
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect
from .forms import PostForm
from .models import Post
# Create your views here.
def post_create(request):
form = PostForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "Created !!")
return HttpResponseRedirect(reverse('posts:list'))
else:
messages.error(request, "not Created !!")
context = {
"form": form,
"title": "Create Form"
}
return render(request, "posts/post_form.html", context)
def post_detail(request, id=None):
instance = get_object_or_404(Post, id=id)
context = {
"title": instance.title,
"instance": instance
}
return render(request, "posts/post_detail.html", context)
def post_list(request):
queryset = Post.objects.all()
context = {
"queryset": queryset,
"title": "My user List",
}
return render(request, "posts/base.html", context)
def post_update(request, id=None):
instance = get_object_or_404(Post, id=id)
form = PostForm(request.POST or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "saved !!")
return HttpResponseRedirect(reverse('posts:detail', args=id))
context = {
"title": instance.title,
"instance": instance,
"form": form
}
return render(request, "posts/post_form.html", context)
def post_delete(request, id=None):
instance = get_object_or_404(Post, id=id)
instance.delete()
messages.success(request, "Deleted !!")
return redirect('posts:list')
继承我的post_detail.html
{% extends "posts/base.html" %}
{% block content %}
<h1>{{ title }}</h1>
<p><a href='{% url "posts:list" %}'>Back</a></p>
<p><a href='{% url "posts:delete" instance.id %}'>delete</a></p>
<h3>{{instance.title}}</h3>
<p>{{instance.content}}</p>
<p>{{instance.timestamp}}</p>
<p>{{instance.updated}}</p>
<p>{{instance.id}}</p>
{% endblock content %}
继承我的post_form.html
{% extends "posts/base.html" %}
{% block content %}
{{ block.super }}
<h1>Edit: {{ title }}</h1>
<form method='post' action=''>{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create Post">
</form>
{% endblock content %}}
继承我的base.html
<html>
<body>
{% if messages %}
<div class="messages">
<ul class="messages">
{% for message in messages %}
<li {% if message.tags %} class="{{ message.tags }}" {% endif %} >{{ message }} </li>
{% endfor %}
</ul>
{%endif%}
<div class="container">
{% block content %}
<p>parent page</p>
<h1>{{ title }} is working</h1>
{% for p in queryset %}
<a href='{% url "posts:detail" p.id %}'>
<h3>{{p.title}}</h3>
</a>
{% if user.is_authenticated %}
<a href='{% url "posts:update" p.id %}'>edit</a>
<a href='{% url "posts:delete" p.id %}'>delete</a>
{% endif %}
<p>{{p.content}}</p>
<p>{{p.timestamp}}</p>
<p>{{p.updated}}</p>
<p>{{p.id}}</p>
<hr>
{% endfor %}
{% endblock content %}
</div>
</body>
</html>
我的追溯
环境:
Request Method: POST
Request URL: http://localhost:8000/posts/16/edit/
Django Version: 1.9.1
Python Version: 3.5.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts.apps.PostsConfig']
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/Users/ray/Desktop/mypy/trydjango/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/Users/ray/Desktop/mypy/trydjango/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/ray/Desktop/mypy/trydjango/src/posts/views.py" in post_update
63. return HttpResponseRedirect(reverse('posts:detail', args=id))
File "/Users/ray/Desktop/mypy/trydjango/lib/python3.5/site-packages/django/core/urlresolvers.py" in reverse
600. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/Users/ray/Desktop/mypy/trydjango/lib/python3.5/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix
508. (lookup_view_s, args, kwargs, len(patterns), patterns))
Exception Type: NoReverseMatch at /posts/16/edit/
Exception Value: Reverse for 'detail' with arguments '('1', '6')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['posts/(?P<id>\\d+)/$']
非常感谢任何有关如何解决此问题的建议
答案 0 :(得分:3)
应用程序没有损坏,这只是您需要解决的代码中的一个错误。 你的问题在这里:
reverse('posts:detail', args=id)
应该是
reverse('posts:detail', args=(id, )) #or even args=[id]
args
期待一个列表,并且由于您将其发送为“16”,因此它被解释为[“1”,“6”]并且没有任何内容与该模式匹配。
通过明确发送列表,您可以确保发送的id
确实是“16”而不是列表。
答案 1 :(得分:0)
而不是:
return HttpResponseRedirect(reverse('posts:detail', args=id))
尝试:
return HttpResponseRedirect(reverse('posts:detail', args=[id]))