我在试着为我的博客添加评论功能,但现在遇到了一个错误,而且我不清楚具体原因是什么。
错误信息:
NoReverseMatch at /2024/01/01/lesson-1/
Reverse for 'post_comment' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/(?P<lesson>[-a-zA-Z0-9_]+)/comment/$']
错误高亮发生在:
<form action="{% url 'lang_learning_app:post_comment' post.id %}" method="post">
urls.py 文件:
urlpatterns = [
...
path('<int:year>/<int:month>/<int:day>/<slug:lesson>/', views.lesson_detail, name='lesson_detail'),
path('<int:year>/<int:month>/<int:day>/<slug:lesson>/comment/', views.post_comment, name='post_comment'),
...]
forms.py 文件:
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['name', 'email', 'body']
models.py 文件:
class Lesson(models.Model):
# ...
class Comment(models.Model):
# ...
views.py 文件:
@require_POST
def post_comment(request, post_id):
post = get_object_or_404(Lesson, id=post_id, status=Lesson.Status.PUBLISHED)
# ...
comment_form.html 文件:
<h2>Add a new comment</h2>
<form action="{% url 'lang_learning_app:post_comment' post.id %}" method="post">
{{ form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Add comment"></p>
</form>
lesson_detail.html 文件:
{% with comments.count as total_comments %}
<h2>
{{ total_comments }} comment{{ total_comments|pluralize }}
</h2>
{% endwith %}
{% for comment in comments %}
<div class="comment">
<p class="info">
Comment {{ forloop.counter }} by {{ comment.name }}
{{ comment.created }}
</p>
{{ comment.body|linebreaks }}
</div>
{% empty %}
<p>There are no comments yet.</p>
{% endfor %}
{% include "lessons/comment_form.html" %}
我不确定为何遇到这个错误,我已经遵循了《Django实战》这本书中的指导,并针对我的博客做了一些调整,将“post”改为了“lesson”。你能帮我分析一下为什么会遇到这个错误吗?
提前感谢!