我目前正在为一个项目撰写博客,我想为DetailView中的每个帖子添加评论部分。我的代码看起来不错,但是我不断收到“找不到页面(404)错误”。我认为这可能是我的网址格式,但我似乎无法弄清楚自己在做什么错。
给出错误url.py
urlpatterns[
path('blog/post/<int:pk>/', views.PostDetailView.as_view(),name='post_detail'),
path('blog/post/<int:pk>/comment/', views.MyFormView.as_view(), name='my_form_view_url'),
]
forms.py
class CommentForm(forms.ModelForm):
class Meta():
model = Comment
fields = ('text',)
widgets = {
'text': forms.Textarea(attrs={'class':'ediable medium-editor-textarea'})
}
views.py
class PostDetailView(DetailView):
model = Post
template_name = 'carsforsale/post_detail.html'
def get_context_data(self, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs)
context['form'] = CommentForm()
return context
class MyFormView(SingleObjectMixin,FormView):
template_name = 'carsforsale/post_detail.html'
form_class = CommentForm
model = Comment
def post(self, request, *args, **kwargs):
self.object = self.get_object()
return super().post(request, *args, **kwargs)
def get_success_url(self):
return reverse('carsforsale:post_detail', kwargs={'pk': self.object.pk})
post_detail.html
这是post_detail.html
中的表格 <form method="POST" action="{% url 'carsforsale:my_form_view_url' pk=post.pk %}">
{% csrf_token %}
<div class="form-group">
{% render_field form.text class="form-control text" rows=3 %}
</div>
<input type="submit" class="btn btn-primary" value="Comment" />
</form>
这些是我的帖子和评论模型
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete= models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
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 approve_comments(self):
return self.comments.filter(approved_comment=True)
def get_absolute_url(self):
return reverse("post_list")
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey('carsforsale.Post', related_name='comments', on_delete = models.CASCADE)
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def get_absolute_url(self):
return reverse("carsforsale:post_detail",kwargs={'pk':self.pk})
def __str__(self):
return self.text
答案 0 :(得分:1)
大概MyURLView的URL中的pk是指注释将要附加到的帖子。但是视图本身具有注释的模型属性,因此这是Django尝试加载的模型。带有那个pk的注释不存在,因此是错误的。
您将需要覆盖get_object
来直接执行查询并返回对象。您还需要覆盖form_valid
才能将新评论与该帖子相关联。
def get_object(self, **kwargs):
return get_object_or_404(Post, pk=self.kwargs["pk"]
def form_valid(self, form):
form.instance.post = self get_object()
return super().form_valid(form)