Django 3 'NoReverseMatch 在 /post/1/

dan*_*443 2 python django django-models jinja2

我的博客有发帖子的能力。我想要一个可以更新/编辑博客的功能,当我尝试实现该功能时,我遇到了以下错误;

NoReverseMatch at /post/1/ 未找到带有参数 '('',)' 的 'post_edit' 反向匹配。尝试了 1 个模式:['post/(?P[0-9]+)/edit/$']

我知道哪一行导致了问题:

/post_detail.html
<a href="{% url 'post_edit' post.pk %}"> +Edit Blog Post</a>
Run Code Online (Sandbox Code Playgroud)

如果没有上面的线,我就不会收到任何错误。我只是一个学习 Django 的初学者,我无法理解为什么这不起作用。我正在遵循的教程中建议了这一点。

/urls.py

urlpatterns = [
    path('post/<int:pk>/edit/', BlogUpdateView.as_view(), name='post_edit'), # new
    path('post/new/', BlogCreateView.as_view(), name='post_new'),
    path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'),
    path('', BlogListView.as_view(), name='home'),
]
Run Code Online (Sandbox Code Playgroud)

/post_detail.html

 {% extends 'base.html' %}

{%  block content %}
<div class="post-entry">
    <h2>
        {{ my_posts.title }}
    </h2>
    <p>
        {{ my_posts.body }}
    </p>
</div>

<a href="{% url 'post_edit' post.pk %}"> +Edit Blog Post</a>

{% endblock content %}
Run Code Online (Sandbox Code Playgroud)

视图.py

class BlogListView(ListView):
    model = Post
    template_name = 'home.html'


class BlogDetailView(DeleteView):
    model = Post
    context_object_name = 'my_posts'
    template_name = 'post_detail.html'

class BlogCreateView(CreateView):
    model = Post
    template_name = 'post_new.html'
    fields = '__all__'

class BlogUpdateView(UpdateView):
    model = Post
    template_name = 'post_edit.html'
    fields = ['title', 'body']
Run Code Online (Sandbox Code Playgroud)

/models.py

class Post(models.Model):

    title = models.CharField(max_length=200)
    author = models.ForeignKey(
        'auth.User',
        on_delete=models.CASCADE,
    )
    body = models.TextField()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post_detail', args=[str(self.id)])
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 5

您的上下文对象的名称是:context_object_name = 'my_posts',而不是'post'。因此该对象位于my_posts您的模板中。

因此,链接应该是:

<a href="{% url 'post_edit' my_posts.pk %}"> +Edit Blog Post</a>
Run Code Online (Sandbox Code Playgroud)