[英]Django 3 'NoReverseMatch at /post/1/
我的博客有發表帖子的能力。 我想要一個可以更新/編輯博客的功能,當我嘗試實現該功能時,我遇到了以下錯誤;
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 %}
視圖.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']
/模型.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' my_posts.pk %}"> +Edit Blog Post</a>
嘗試:
path(r'post/<int:pk>/edit/', BlogUpdateView.as_view(), name='post_edit'), # new
我在你的網址前面加了一個r
。
我們可以使用或不使用 context_object_name 以小寫形式編寫模型類名稱“post”或“object”以使其工作。 <a
<a href="{% url 'post_edit' post.pk %}">+ edit post</a> or <a href="{% url 'post_edit' object.pk %}">+ edit post</a>
在 post_detail.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.