class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
text = models.TextField()
image = models.ImageField(upload_to='Comment_Pictures', blank=True)
date_posted = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.text
def get_absolute_url(self):
return '/'
class CommentAddView(LoginRequiredMixin, CreateView):
model = Comment
fields = ['text', 'image']
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.post = Post.objects.get(id=self.kwargs['pk'])
return super().form_valid(form)
class CommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Comment
success_url = '/'
def test_func(self):
comment = self.get_object()
if request.user == comment.author:
return True
return False
/ post / 3 / comment /'dict'对象中的TypeError不可调用 方法:POST请求URL:http://localhost:8000/post/3/comment/ Django 版本:2.1.7异常类型:TypeError异常值:'dict' 对象不可调用
答案 0 :(得分:6)
错误告诉您确切的错误。 self.kwargs
是字典,但是您正在调用它。
您可能是说:
data = Post.objects.get(id=self.kwargs['pk'])
答案 1 :(得分:0)
您也可以尝试以下操作:
form.instance.post = Post.objects.get(id=self.kwargs.get('pk'))