【问题标题】:Django IntegrityError 'author_id' violates not-null constraintDjango IntegrityError 'author_id' 违反非空约束
【发布时间】:2021-01-21 01:23:11
【问题描述】:

我不知道为什么 Django 在我尝试发布评论表单时会引发 IntegrityError。它迫使我将作者和 halp 定义为null=Trueblank=True,但我不想这样做。在我的项目中,当有人发表评论时,作者和附加的帖子(halp)不能为空。

第一个:“author_id”违反了非空约束

第二个:“halp_id”违反了非空约束

models.py:

class Comment(models.Model):
    STATE_CHOICES = [
        ('open', _('Ouvert')),
        ('deleted', _('Supprimé'))
    ]

    halp = models.ForeignKey("Halp", on_delete=models.CASCADE)
    text = models.TextField()
    comment = models.ForeignKey("self", on_delete=models.CASCADE, related_name="comment_child", null=True, blank=True)
    date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    state = models.CharField(max_length=20, choices=STATE_CHOICES, default='open')
    is_solution = models.BooleanField(default=False)

    class Meta:
        ordering = ['halp', '-id']

    def __str__(self):
        return self.halp.title

    def get_text(self):
        return self.text[:20]

forms.py:

class CommentForm(forms.ModelForm):
    text = forms.CharField(
        label='',
        widget=forms.Textarea(attrs={
            'class': 'form-control form-custom',
            'placeholder': _('Redigez une réponse ou un commentaire...')
        })
    )

    class Meta:
        model = Comment
        fields = ['text']

views.py:

class CommentCreate(LoginRequiredMixin, CreateView):
    model = Comment
    form_class = forms.CommentForm

    def form_valid(self, form):
        text = form.cleaned_data['text']
        self.halp = Halp.objects.get(slug=self.kwargs['slug'])

        self.comment = Comment.objects.create(
            text=text,
            author=self.request.user,
            halp=self.halp,
        )

        return super(CommentCreate, self).form_valid(form)

    def get_success_url(self, **kwargs):
        return reverse_lazy('forum:halp-detail', kwargs={'slug': self.halp.slug})

如果有人可以帮助我,我想我错过了一些东西。提前谢谢你。

最好的问候。

【问题讨论】:

    标签: python django database postgresql forms


    【解决方案1】:

    将您的 form_valid(...) 方法更改为,

    from django.http import HttpResponseRedirect
    
    
    class CommentCreate(LoginRequiredMixin, CreateView):
        model = Comment
        form_class = forms.CommentForm
    
        def form_valid(self, form):
            comment = form.save(commit=False)
            comment.author = self.request.user
            comment.halp = Halp.objects.get(slug=self.kwargs['slug'])
            comment.save()
            self.object = comment
            return HttpResponseRedirect(self.get_success_url())
    
        def get_success_url(self, **kwargs):
            return reverse_lazy('forum:halp-detail', kwargs={'slug': self.kwargs['slug']})

    【讨论】:

    • 天哪,谢谢你!你能解释一下我为什么错了吗?
    • 因为你没有设置FK值正确commit=False会创建一个dummy模型对象,您可以附加/分配 FK 值。 @Beno
    猜你喜欢
    • 2020-08-20
    • 2016-10-21
    • 2019-04-08
    • 2017-10-15
    • 2014-04-05
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多