我正在使用django的通用CreateView为我的网站构建评论系统。允许用户对电影发表评论。这是我的评论模型-
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comments", on_delete=models.CASCADE)
body = models.TextField()
movie = models.ForeignKey(Movie, related_name="comments", on_delete=models.CASCADE)
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
class Meta:
ordering = ('created',)
def __str__(self):
return "comment by {} on {}".format(self.user.first_name, self.movie)
这是我正在使用的CreateView-
class AddComment(LoginRequiredMixin, CreateView):
form_class = CommentForm
def get_initial(self):
initial = super().get_initial()
#for providing initial values to the form
initial['user'] = self.request.user.id
initial['movie'] = self.kwargs['movie_id']
return initial
def get_success_url(self):
movie_id = self.kwargs['movie_id']
return reverse('detail', kwargs={'pk':movie_id})
def render_to_response(self, context=None, **response_kwargs):
movie_id = self.kwargs['movie_id']
return redirect(to = reverse('detail', kwargs={'pk':movie_id}))
这是评论表-
class CommentForm(forms.ModelForm):
user = forms.ModelChoiceField(widget=forms.HiddenInput, queryset=get_user_model().objects.all())
movie = forms.ModelChoiceField(widget=forms.HiddenInput, queryset=Movie.objects.all())
class Meta:
model = Comment
fields = ('user','movie', 'body')
我正在尝试将评论与用户和电影相关联。因此,我使用了get_initial()方法来用初始数据填充表单,因为发布的数据中不存在用户和电影。但是总以某种方式form.is_valid()总是错误的。我不知道我哪里做错了。请帮忙。
如果有帮助,我尝试通过覆盖get_form_kwargs函数来打印出用于实例化表单对象的kwargs的值来调试程序,
{
'initial': {'user': 1, 'movie': 2}, 'prefix': None,
'data': <QueryDict: {'csrfmiddlewaretoken': ['wFmkOMLAcIszMc17GsBsqPhyaZnJEXb0TRNteKd9sgjYKEF3jvqwsQ3Noik3DHq6'], 'body': ['best movie ever\r\n'], 'user': [''], 'movie': ['']}>, 'files': <MultiValueDict: {}>
}
答案 0 :(得分:0)
Well,User和Movie是外键字段,因此它们希望接收相关模型的对象作为首字母。您正在尝试使用pk(int)代替这些对象。 它应该如下所示:
def get_initial(self):
initial = super().get_initial()
#for providing initial values to the form
initial['user'] = self.request.user
initial['movie'] = Movie.objects.get(pk=movie_id)
return initial.copy()