【问题标题】:Django 3 'NoReverseMatch at /post/1/Django 3 'NoReverseMatch at /post/1/
【发布时间】:2019-12-27 21:42:58
【问题描述】:

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

NoReverseMatch at /post/1/ Reverse for 'post_edit' with arguments '('',)' 未找到。尝试了 1 种模式:['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 %}

views.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)])

【问题讨论】:

  • 试试这个 +编辑博文
  • "{% url 'post_edit' my_posts.pk %}" 而不是"{% url 'post_edit' post.pk %}"
  • 谢谢你,Willem,添加你的评论作为答案,我把它标记为正确。我不敢相信我忘记了我重新分配了它
  • context_object_name'my_posts',而不是 'post'
  • 与DRF无关的请不要提及

标签: python django django-models jinja2


【解决方案1】:

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

因此链接应该是:

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

【讨论】:

    【解决方案2】:

    试试:

    path(r'post/<int:pk>/edit/', BlogUpdateView.as_view(), name='post_edit'), # new
    

    我在您的网址前添加了r

    【讨论】:

      【解决方案3】:

      我们可以将模型类名称“post”写成小写或“object”,无论是否带有 context_object_name 都可以使其工作。

      <a href="{% url 'post_edit' post.pk %}">+ edit post</a>
      or
      <a href="{% url 'post_edit' object.pk %}">+ edit post</a>

      在 post_detail.html

      【讨论】:

        猜你喜欢
        • 2020-06-01
        • 2017-08-19
        • 2020-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-01
        • 1970-01-01
        相关资源
        最近更新 更多