简体   繁体   English

获取数据库错误,NOT NULL 约束失败

[英]Getting database error, NOT NULL constraint failed

I'm creating a User registration form with the AbstractBaseUser, I have got to the point where when I press "Create" on my page it should save the fields to the Database however, I keep getting the following error message:我正在使用 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

I don't quite understand why it says NOT NULL constraint failed: account_account.first_name.我不太明白为什么它说 NOT NULL 约束失败:account_account.first_name。 I have nothing related to a first name field/model in my code.我的代码中与名字字段/模型没有任何关系。

Prior to getting this error, I did have the first_name field as a required field in the registration process but I deleted the field any I think I deleted everything related to it.在收到此错误之前,我确实在注册过程中将 first_name 字段作为必填字段,但我删除了任何我认为我删除了与它相关的所有内容的字段。 I don't know what to do.我不知道该怎么办。 I have tried deleted migrations and running them again and deleting the pycache.我已经尝试删除迁移并再次运行它们并删除 pycache。

Here is my models.py file:这是我的 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

Here is my views.py file:这是我的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)

Finally, here is my forms.py file:最后,这是我的 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")

i think when you created your project for the first time, you followed the tutorial and ran:我认为当您第一次创建项目时,您按照教程运行:

python manage.py makemigrations
python manage.py migrate

because of these commands, your app make DB for django.contrib.auth.models.User (which you try to change here and build new User model).由于这些命令,您的应用程序为 django.contrib.auth.models.User (您尝试在此处更改并构建新的用户模型)创建数据库。 so first of all you need to delete your db.sqlite file.所以首先你需要删除你的 db.sqlite 文件。
and then delete all migrations inside migrations folder, and delete pycache folders too.然后删除迁移文件夹中的所有迁移,并删除pycache文件夹。
but careful you must keep __init__file not deleted.但请注意,您必须保持 __init__file 不被删除。
after than run those commands again and everything will be fine:之后再次运行这些命令,一切都会好起来的:

python manage.py makemigrations
python manage.py migrate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM