现在,我正在创建一个网站。在这个网站上,我创建了一个帖子部分。我可以添加新帖子-我是说,当我添加一些内容时,可以在管理面板中看到- 但是点击“保存”后,就会发生这种情况
NoReverseMatch at /post/new/
Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name.
blog / views.py
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {})
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
blog / post_detail.html
{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endblock %}
blog / urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/new/$', views.post_new, name='post_new'),
]
我该如何解决?
答案 0 :(得分:1)
在进行以下操作时,您需要创建另一个view
和url
,它们的名称为post_detail
。
def post_new(request):
...
# here it will look to `urls.py` and will search the url with the name
# post_detail, but you don't have it.
return redirect('post_detail', pk=post.pk)
简单创建新的url
和view
。
blog / urls.py
urlpatterns = [
...
url(r'^post/detail/$', views.post_detail, name='post_detail'),
]
blog / views.py
def post_detail(request, post_id):
# do something