且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NOT NULL约束失败,Django CreateView失败

更新时间:2023-12-04 09:16:52

您在这里有一个错字,您覆盖了 form_valid ,但是您写了 post_valid

You have a typo there, you are overriding form_valid but you have written post_valid.

def form_valid(self, form):
    review = form.save(Commit=False)
    review.lawyer = get_object_or_404(Lawyer, 
                                        slug=self.kwargs.get('slug'))
    review.reviewer = User.objects.get(user=self.request.user)

    # save and return HttpResponse
    review.save()
    return HttpResponseRedirect(self.get_success_url())

但是, super 调用仍将调用父类的 form_valid 仍然会引发错误。我认为您可以将评论保存在此重写的方法中,并返回基类返回的内容,即 return HttpResponseRedirect(self.get_success_url())

But, the super call will still call the parent class' form_valid which will still raise the error. I think you can save the review in this overriden method and return what the base class returns i.e. return HttpResponseRedirect(self.get_success_url())

引用: form_valid in FormMixin类,在ModelFormMixin中 form_valid班级

Ref: form_valid in FormMixin class, form_valid in ModelFormMixin class