python - 如何处理 Django 中的 NoReverseMatch 错误
问题描述
我在下面遇到此错误:Reverse for 'post_detail' with no arguments not found。尝试了 1 种模式:['(?P[-a-zA-Z0-9_]+)/$']。
我正在开发一个博客应用程序。当您在索引页面的仪表板上单击查看更多文章时,post_detail.html 应显示完整文章并允许用户发表评论。单击查看文章后,我不断收到上面发布的错误。
这是 post_detail.html 代码
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-8 card mb-4 mt-3 left top">
<div class="card-body">
<h1>{% block title %} {{ post.title }} {% endblock title %}</h1>
<p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p>
<p class="card-text ">{{ post.content | safe }}</p>
</div>
</div>
<div class="col-md-8 card mb-4 mt-3 ">
<div class="card-body">
<!-- comments -->
{% with comments.count as total_comments %}
<h2>{{ total_comments }} comments</h2>
<p>
{% endwith %} {% for comment in comments %}
</p>
<div class="comments" style="padding: 10px;">
<p class="font-weight-bold">
{{ comment.name }}
<span class=" text-muted font-weight-normal">
{{ comment.created_on }}
</span>
</p>
{{ comment.body | linebreaks }}
</div>
{% endfor %}
</div>
</div>
<div class="col-md-8 card mb-4 mt-3 ">
<div class="card-body">
{% if new_comment %}
<div class="alert alert-success" role="alert">
Your comment is awaiting moderation
</div>
{% else %}
<h3>Leave a comment</h3>
<form method="POST" action="{% url 'post_detail' %}" style="margin-top: 1.3em;">
{{ comment_form | crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock content %}
我的模型
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True, blank= True, null=True)
updated_on = models.DateTimeField(auto_now= True)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-published_date']
def publish(self):
self.published_date=timezone.now()
self.save()
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_on']
def __str__(self):
return 'Comment {} by {}'.format(self.body, self.name)
查看 post_detail
def post_detail(request, slug):
template_name = 'post_detail.html'
post = get_object_or_404(Post, slug=slug)
comments = post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
context = {'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form}
return render(request, 'blog/post_detail.html', context)
网址
urlpatterns = [
path('', views.index, name='index'),
#path('', views.PostList.as_view(), name='index'),
path('login', views.login, name= 'login'),
path('logout', views.logout, name= 'logout'),
path('register', views.register, name = 'register'),
path('dashboard', views.dashboard, name = 'dashboard'),
path('posts', views.posts, name = 'posts'),
path('articles', views.articles, name='articles'),
path('prayers', views.prayers,name='prayers' ),
path('prayer_request', views.prayers, name='prayer_request'),
path('<slug:slug>/', views.post_detail, name='post_detail'),
path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='registration/password_change_done.html'),
name='password_change_done'),
path('password_change/', auth_views.PasswordChangeView.as_view(template_name='registration/password_change.html'),
name='password_change'),
path('password_reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_done.html'),
name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'),
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'),
name='password_reset_complete'),
]
请帮助解决此错误。
解决方案
在您的 urls.py 之后,您应该沿着您的 post_detail url 传递一个 slug。因此,在您的表单中,如果没有这样的蛞蝓,您就无法调用您的网址<form method="POST" action="{% url 'post_detail' %}">
因为你不能轻易知道你的新帖子的 id,也许应该创建一个不同的 url 来创建一个新帖子,比如 post_create
推荐阅读
- python - 从两个不同的表中找到最小值最大值
- r - 分母 自由度 Anova 混合设计 Type III
- kml - 更新 Google KMZ 弹出内容并删除 FME 中的“方向”
- windows - 如何将 Jenkins 管道变量用于 powershell 或 cmd 代码?
- apache-spark - 在连接列的*子集*上分区时,无需随机播放的 Spark 连接
- javascript - 如何过滤掉 MarkLogic 中的非 json 文档?
- html - 为什么文本显示为单行而不是 4 行?
- reactjs - 为什么 useRef 在这种情况下不触发子重新渲染?
- javascript - Highcharts:如何在`mouseOver`事件中获取Angular组件上下文
- python - 在 Python Asyncio 上,我试图将一个函数的值返回到另一个函数