完整性错误,元素无法添加

时间:2016-08-15 06:27:08

标签: django

当我决定将我的模型绑定到用户,数据库时,出了点问题。我猜我的模型有问题。任何帮助将非常感激。

models.py

class Word(models.Model):
  name=models.CharField(max_length=100,unique=True)
  translation=models.CharField(max_length=255)
  created_at=models.DateTimeField(auto_now_add=True)
  times_used=models.IntegerField(default=0,editable=False)
  user=models.ForeignKey(User,related_name='created_by',null=False)

当我尝试创建元素时,会显示以下消息:

 IntegrityError at /words/
 NOT NULL constraint failed: words_word.user_id

views.py:

class Create_Word(generic.CreateView):
    model=Word
    fields=['name','translation',]
    template_name = "words/list_all.html"

1 个答案:

答案 0 :(得分:1)

您必须明确地将当前用户分配到该字段,auto_now_add没有ForeignKey

class CreateWord(CreateView):
    model = Word
    fields=['name','translation',]
    template_name = "words/list_all.html"

    def form_valid(self, form):
        word = form.save(commit=False)
        word.user = self.request.user
        return super(CreateWord, self).form_valid(form)