我正在尝试使用django为我的博客应用编辑现有的博客文章,但它说的是以下(我是一种新手,我确实尝试自己找到解决方案,但无法和#39; T:
这里出现了错误:
Reverse for 'post_edit' with arguments '()' and keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/edit/$']
这是我的urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail),
url(r'^post/new/$', views.post_new, name='post_new'),
url(r'^post/(?P<pk>[0-9]+)/edit/$', views.post_edit, name='post_edit'),
]
我的views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from . models import Post
from . forms import PostForm
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')[:3]
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
postdetail = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'postdetail': postdetail})
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('blog.views.post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('blog.views.post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'blog/post_edit.html', {'form': form})
post_details页面(当我删除超链接时,我能够查看我的post_details
页面:
{% extends "blog/base.html" %}
{% block content %}
<article id="article">
<div class="container">
<div class="post-detail">
{% if postdetail.published_date %}
<h2>{{ postdetail.title }}</h2>
<p>{{ postdetail.text }}</p>
<small>{{ postdetail.published_date }}</small>
{% endif %}
<a href="{% url "post_edit" pk=post.pk %}">Edit this Post</a>
</div>
</div>
{% endblock content %}
答案 0 :(得分:2)
应该是postdetail.pk
而不是post.pk
,因为您在上下文中传递postdetail
而不是post
。
<a href="{% url "post_edit" pk=postdetail.pk %}">Edit this Post</a>
当您使用post.pk
时,post_edit
视图正在pk
选择''
(来自上面的错误),因为其中没有post
上下文,因此没有网址能够与您的post_edit
视图匹配,从而导致错误。