python - Django 3 'NoReverseMatch 在/post/1/

标签 python django django-models jinja2

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

NoReverseMatch at /post/1/ Reverse for 'post_edit' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/edit/$']

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

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

如果没有上面的线,我就不会收到任何错误。我只是一个学习 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'),
]

/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 %}

View .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']

/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)])

最佳答案

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

链接应该是:

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

关于python - Django 3 'NoReverseMatch 在/post/1/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59506293/

相关文章:

python - 使用 Python 的 Gmail 中的 IMAP 问题

python - 逻辑回归的批量梯度下降

python - 使用地址在 python 进程之间共享 ctype 内存

django - 实用(Django)缓存策略和实现?缓存长,数据更改时缓存无效

MySQL 添加外键约束失败

python - django 中的 post_save 立即更新实例

python - 以 "w"模式打开文件 : IOError: [Errno 2] No such file or directory

python - 无法在 CentOS v8 上通过 yum 安装 mod_wsgi

Django sorl-thumbnail不显示图像

Python - 使用 auth.User 模型作为 OneToOneField 的 Django 查询