【问题标题】:Getting database error, NOT NULL constraint failed获取数据库错误,NOT NULL 约束失败
【发布时间】:2020-10-28 05:28:50
【问题描述】:

我正在使用 AbstractBaseUser 创建一个用户注册表单,当我在页面上按“创建”时,它应该将字段保存到数据库中,但是,我不断收到以下错误消息:

Traceback (most recent call last):
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\dylan\myblogsite\account\views.py", line 11, in registration_view
    form.save()
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\forms.py", line 137, in save
    user.save()
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\base_user.py", line 66, in save
    super().save(*args, **kwargs)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 745, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 782, in save_base
    updated = self._save_table(
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 887, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 924, in _do_insert
    return manager._insert(
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1204, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1392, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: account_account.first_name

我不太明白为什么它说 NOT NULL 约束失败:account_account.first_name。我的代码中没有与名字字段/模型相关的任何内容。

在收到此错误之前,我确实在注册过程中将 first_name 字段作为必填字段,但我删除了任何我认为我删除了与它相关的所有内容的字段。我不知道该怎么办。我已尝试删除迁移并再次运行它们并删除 pycache。

这是我的 models.py 文件:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager


class MyAccountManager(BaseUserManager):
    def create_user(self, email, username, password=None):
        if not email:
            raise ValueError("Users must have an email address")
        if not username:
            raise ValueError("Users must have an username")

        user  = self.model(
                email=self.normalize_email(email),
                username=username,
            )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, password):
        user  = self.create_user(
                email=self.normalize_email(email),
                password=password,
                username=username,
            )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user


class Account(AbstractBaseUser):
    email                   = models.EmailField(verbose_name="email", max_length=60, unique=True)
    username                = models.CharField(max_length=30, unique=True)
    date_joined             = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
    last_login              = models.DateTimeField(verbose_name='last login', auto_now=True)
    is_admin                = models.BooleanField(default=False)
    is_active               = models.BooleanField(default=True)
    is_staff                = models.BooleanField(default=False)
    is_superuser            = models.BooleanField(default=False)


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = MyAccountManager()

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

这是我的views.py文件:

from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from account.forms import RegistrationForm


def registration_view(request):
    context = {}
    if request.POST:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            email = form.cleaned_data.get('email')
            raw_password = form.cleaned_data.get('password1')
            account = authenticate(email=email, password=raw_password)
            login(request, account)
            return redirect('home')
        else:
            context['registration_form'] = form
    else: #GET request
        form = RegistrationForm()
        context['registration_form'] = form
    return render(request, 'register.html', context)

最后,这是我的 forms.py 文件:

from django import forms
from django.contrib.auth.forms import UserCreationForm

from account.models import Account


class RegistrationForm(UserCreationForm):
    email = forms.EmailField(max_length=60, help_text='Required. Add a valid email address')

    class Meta:
        model = Account
        fields = ("email", "username", "password1", "password2")

【问题讨论】:

  • 你确定你没有继承AbstractUser,而不是AbstractBaseUserAbstractUser 定义了first_namelast_name 等字段。
  • 根据您的错误转储,这是在抱怨的数据库。 account 表可能仍然有一个 first_name 列,该列受到 not null 的约束。
  • 您删除了迁移?
  • @EdwinCruz 不是迁移文件夹,而是文件夹中的迁移是的。
  • 你应该删除sql lite文件,然后重新运行你的makemigrationsmigrate命令

标签: python html python-3.x django python-2.7


【解决方案1】:

我认为当您第一次创建项目时,您按照教程运行:

python manage.py makemigrations
python manage.py migrate

由于这些命令,您的应用会为 django.contrib.auth.models.User 创建数据库(您尝试在此处更改并构建新的用户模型)。 所以首先你需要删除你的 db.sqlite 文件。
然后删除 migrations 文件夹中的所有迁移,并删除 pycache 文件夹。
但请注意,您必须保持 __init__file 不被删除。
之后再次运行这些命令,一切都会好起来的:

python manage.py makemigrations
python manage.py migrate

【讨论】:

    猜你喜欢
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-31
    • 1970-01-01
    • 2015-04-22
    • 2021-12-17
    • 2018-08-24
    相关资源
    最近更新 更多