我想为帖子对象创建评论页面,其中帖子对象正在使用DetailView,并且在下面我想使用CommentForm来添加评论。我遵循了official docs,但被卡住了。我收到404错误。
因此,从一开始,我在models.py
中有两个模型:
class Post(models.Model):
content = models.TextField(max_length=280, validators=[MaxLengthValidator(280)])
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='comments')
text = models.TextField(max_length=280)
date_created = models.DateTimeField(auto_now_add=True)
然后我有views.py
:
class PostDetailView(DetailView):
model = Post
context_object_name = 'post'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = CommentForm()
return context
class CommentCreateView(SingleObjectMixin, FormView):
model = Comment
form_class = CommentForm
template_name = 'social/post_detail.html'
def form_valid(self, form):
form.instance.author = self.request.user.userprofile
return super().form_valid(form)
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden('')
# It crashes here!
self.object = self.get_object()
return super().post(request, *args, **kwargs)
def get_success_url(self):
return reverse('post-detail', kwargs={'pk': self.object.pk})
class PostDetail(View):
def get(self, request, *args, **kwargs):
view = PostDetailView.as_view()
return view(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
view = CommentCreateView.as_view()
return view(request, *args, **kwargs)
经过少量调试后,我发现它在执行第self.object = self.get_object()
行时崩溃了
urls.py
path('post/<int:pk>/', PostDetail.as_view(), name='post-detail'),
错误本身:
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/post/3/
Raised by: social.views.PostDetail
No comment found matching the query
怎么了?
CommentForm:
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['text']
终端也出错:
Not Found: /post/3/
[WARNING] [09:12:24] [django.request.log_response] -> Not Found: /post/3/
[20/Nov/2019 09:12:24] "POST /post/3/ HTTP/1.1" 404 1730
所以我想到的是get_object()
方法试图获取在kwargs中传递的id的注释。但是,该ID是帖子的ID,而不是评论的ID,并且由于在DB中根本没有评论,因此在这种情况下,ID号为'3'的评论也没有。
此外,如果我尝试获取self.model.id/pk
,它应该是DefferedAtribute注释的ID。
这只是我的猜测。我不确定。