简体   繁体   English

django.db.utils.IntegrityError: NOT NULL 约束失败:accounts_user.user_id

[英]django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_user.user_id

I'm trying to create a multiple user model in django.我正在尝试在 django 中创建一个多用户 model。 I am new to django and as such not in a position to get the exact result I need.我是 django 的新手,因此不在 position 中以获得我需要的确切结果。

I get an error when trying to createsuperuser.尝试创建超级用户时出现错误。

Here is my models.py这是我的models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

ROLES =(
        ('main', 'Main'),
        ('teacher', 'Teacher'),
        ('student', 'Student'),
        )

Here's my register and function这是我的寄存器和 function

def Register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')
            password1 = form.cleaned_data.get('password1')
            messages.success(request, f'An account has successfully been created for {first_name} {last_name}. Username is {username} and password is {password1}')
            return redirect('login')
    else:
        form = RegistrationForm()
    return render(request, 'register.html', {'form': form})

class School(models.Model):
    name = models.CharField(max_length=100, null=False, blank=False)

class User(AbstractUser):
    user = models.ForeignKey(School, on_delete=models.PROTECT, null=False, blank=False)
    role = models.CharField(max_length=10, choices=ROLES, blank=False, null=False)


class Teacher(models.Model):
    school = models.ForeignKey(School, on_delete=models.PROTECT, null=False, blank=False)
    name  = models.CharField(max_length=30, blank=False, null=False)
    code = models.CharField(max_length=30, blank=False, null=False)


class Student(models.Model):
    school = models.ForeignKey(School, on_delete=models.PROTECT, null=False, blank=False)
    first_name  = models.CharField(max_length=30, blank=False, null=False)
    last_name = models.CharField(max_length=30, blank=False, null=False)
    adm = models.CharField(max_length=30, blank=False, null=False)

class Main(models.Model):
    school = models.ForeignKey(School, on_delete=models.PROTECT, null=False, blank=False)
    name  = models.CharField(max_length=30, blank=False, null=False)

My admin.py我的管理员.py

from django.contrib import admin
from .models import User, School

admin.site.register(School)
admin.site.register(User)

Trying to create a superuser throws the following traceback尝试创建超级用户会引发以下回溯

(env) D:\Python\Django\Links Online Exams\Links_Online_Results>python manage.py createsuperuser
Username: ptar
Email address: peterolwande@gmail.com
Password:
Password (again):
Traceback (most recent call last):
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: accounts_user.user_id

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
    return super().execute(*args, **options)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\management\base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\models.py", line 157, in create_superuser
    return self._create_user(username, email, password, **extra_fields)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\models.py", line 140, in _create_user
    user.save(using=self._db)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
    super().save(*args, **kwargs)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\base.py", line 753, in save
    self.save_base(using=using, force_insert=force_insert,
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\base.py", line 790, in save_base
    updated = self._save_table(
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\base.py", line 895, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\base.py", line 933, in _do_insert
    return manager._insert(
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\query.py", line 1254, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
    cursor.execute(sql, params)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_user.user_id
class User(AbstractUser):
    user = models.ForeignKey(School, on_delete=models.PROTECT, null=False, blank=False)
    role = models.CharField(max_length=10, choices=ROLES, blank=False, null=False)

In User model, there is a non-nullable field called user which is a ForeignKey to School .User model 中,有一个名为user的不可空字段,它是School的 ForeignKey。

When creating superuser using django management command, it will ask only for username, email, password.当使用 django 管理命令创建超级用户时,它只会询问用户名,email,密码。

In this scenario, user (aka ForeignKey to School) will be empty which is why it is failing with user_id is null.在这种情况下, user (又名 ForeignKey to School)将是空的,这就是它失败的原因, user_id是 null。

There are 2 ways to handle this.有两种方法可以处理这个问题。

  1. Make user field nullable.使user字段可为空。 With this createsuperuser will be able to create new users.有了这个createsuperuser就可以创建新用户了。 Later you can populate user field.稍后您可以填充user字段。
  2. Write your own management command which takes all required fields to create user and the create a superuser.编写您自己的管理命令,该命令采用所有必填字段来创建用户和创建超级用户。

暂无
暂无

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

相关问题 django.db.utils.IntegrityError:NOT NULL 约束失败:users_profile.user_id - django.db.utils.IntegrityError: NOT NULL constraint failed: users_profile.user_id django.db.utils.IntegrityError: NOT NULL 约束失败:user.id - django.db.utils.IntegrityError: NOT NULL constraint failed: user.id Django 表单错误:django.db.utils.IntegrityError:唯一约束失败:legal_useragreedtolegal.user_id - Django form error: django.db.utils.IntegrityError: UNIQUE constraint failed: legal_useragreedtolegal.user_id Django抛出错误django.db.utils.IntegrityError:唯一约束失败:mediaSort_userdata.user_id - Django throwing error django.db.utils.IntegrityError: UNIQUE constraint failed: mediaSort_userdata.user_id 错误:'django.db.utils.IntegrityError: NOT NULL 约束失败:base_user.is_superuser' - Error: 'django.db.utils.IntegrityError: NOT NULL constraint failed: base_user.is_superuser' django.db.utils.IntegrityError:唯一约束失败:core_profile.user_id - django.db.utils.IntegrityError: UNIQUE constraint failed: core_profile.user_id django.db.utils.IntegrityError: NOT NULL 约束失败:app_user.zip - django.db.utils.IntegrityError: NOT NULL constraint failed: app_user.zip django.db.utils.IntegrityError:唯一约束失败:mode_setting.user_id - django.db.utils.IntegrityError: UNIQUE constraint failed: mode_setting.user_id Createsuperuser django.db.utils.IntegrityError: NOT NULL 约束失败 - Createsuperuser django.db.utils.IntegrityError: NOT NULL constraint failed django.db.utils.IntegrityError:NOT NULL约束失败 - django.db.utils.IntegrityError: NOT NULL constraint failed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM