`NOT NULL约束失败:`当尝试创建用户时

时间:2018-06-02 02:34:58

标签: django

我打算创建用户帐户时遇到错误NOT NULL constraint failed:

模型数据代码:

class ActivateCode(models.Model):
    """ """
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    code = models.CharField(max_length=100)
    date_expired = models.DateTimeField(default=tomorrow)

    def __str__(self):
        return self.code

views.py

中的register
def register(request):
    if request.method == "GET":
        form = UserForm()
    if request.method == "POST":
        form = UserForm(request.POST)
        print(vars(form))
        if form.is_valid():
            user = User.objects.create_user(
                      form.cleaned_data['username'],
                      first_name=form.cleaned_data['first_name'],
                      last_name=form.cleaned_data['last_name'],
                      email=form.cleaned_data['email'],
                      password=form.cleaned_data['password'])
            user.is_active = False
            user.save()
            #create activate code
            uuid_code = str(uuid.uuid4()).replace("-", '')
            activate_code = ActivateCode(code=uuid_code)
            activate_code.save()
            return HttpResponse(f"You have registered successfully with activate_code: {uuid_code}. \n"
            "Please activate your account from your registered email.")

它抛出的错误

IntegrityError at /user/register
NOT NULL constraint failed: user_activatecode.user_id
Request Method: POST
Request URL:    http://127.0.0.1:8001/user/register
Django Version: 1.11.13
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: user_activatecode.user_id

如何解决这样的问题?

1 个答案:

答案 0 :(得分:2)

似乎你试图在一个不接受它的字段中插入空值,在你的ActivateCode模型中,它似乎有一个与用户相关的外键,也许你也必须发布它。尝试将用户传递给ActivateCode调用:

ActivateCode(code=code, user=user)