我想创建一个注释部分。我确实做了,但是我的详细信息页面中有一个错误。错误是
*位于/ post / 123 /
的NoReverseMatch找不到带有参数'('',)'的'blog_comment'的反向。尝试了1种模式:['post /(?P \ d +)/ comment / $'] *
这是我的代码。
models.py
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = RichTextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post:detail', kwargs={'slug': self.slug})
class BlogComment(models.Model):
description = models.TextField(max_length=1000, help_text="Enter comment about blog here.")
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
post_date = models.DateTimeField(auto_now_add=True)
blog = models.ForeignKey(Post, on_delete=models.CASCADE)
class Meta:
ordering = ["post_date"]
def __str__(self):
len_title = 75
if len(self.description) > len_title:
titlestring = self.description[:len_title] + '...'
else:
titlestring = self.description
return titlestring
views.py
class BlogCommentCreate(LoginRequiredMixin, CreateView):
model = BlogComment
fields = ['description', ]
def get_context_data(self, **kwargs):
context = super(BlogCommentCreate, self).get_context_data(**kwargs)
context['blog'] = get_object_or_404(Post, pk=self.kwargs['pk'])
return context
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.blog = get_object_or_404(Post, pk=self.kwargs['pk'])
return super(BlogCommentCreate, self).form_valid(form)
def get_success_url(self):
return reverse('blog-detail', kwargs={'pk': self.kwargs['pk'], })
urls.py
url(r'^post/(?P<pk>\d+)/comment/$', views.BlogCommentCreate.as_view, name='blog_comment'),
postcomment_form.html
{% extends 'blog/base.html' %}
{% block content %}
<p>Post your comment for: <a href="{% url 'post_detail' Post.pk %}">{{post.name}}</a></p>
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit" />
</form>
{% endblock %}
post_detail.html
</div>
<div style="margin-left:20px;margin-top:20px">
<h4>Comments</h4>
{% for comment in blog.blogcomment_set.all %}
<hr>
<p>{{ comment.author }} ({{ comment.post_date }}) - {{ comment.description }}</p>
{% endfor %}
<hr>
{% if user.is_authenticated %}
<a href="{% url 'blog_comment' blog.id %}">Add a new comment</a></p>
{% else %}
<p><a href="{% url 'login' %}?next={{ request.path }}">Login</a> to add a new comment</p>
{% endif %}
</div>
很抱歉,我有很多代码。但是我无法理解我所遇到的问题,需要帮助。非常感谢您的帮助。