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