ISSUE ON NOT NULL constraint failed: accounts_user.course_id



我试图在django中创建一个多用户模型。我是一个使用django的初学者,因此不能得到我需要的确切结果。当尝试创建超级用户时,出现错误。

my model.py

*from django.db import models
from admin_dash.models import Course
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class UserManager(BaseUserManager):
def create_user(self,roll,phone,name,password=None):
if not roll:
raise ValueError('You Don't have Permission to do exam')
user = self.model(
roll=roll,
phone=phone,
name=name
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self,roll,phone,name, password):
user = self.create_user(roll,phone,name,password=password)
user.is_admin = True
user.is_staff=True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
phone= models.CharField(verbose_name='phone number', max_length=12,unique=True)
name=models.CharField(max_length=150,null=True)
roll=models.CharField(max_length=20,verbose_name='roll',unique=True)
course=models.ForeignKey(Course,on_delete=models.CASCADE)
date_joind=models.DateTimeField(verbose_name='date joind', auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff=models.BooleanField(default=False)
USERNAME_FIELD = 'roll'
REQUIRED_FIELDS = ['name','phone']
objects = UserManager()
def __str__(self):
return self.name
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True*

This is My admin.py

*from django.contrib import admin
from .import models
# Register your models here.
admin.site.register(models.User)*

尝试创建一个超级用户,我得到以下traceback

*Traceback (most recent call last):
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbbackendsutils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbbackendssqlite3base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: accounts_user.course_id
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocoremanagement__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocoremanagement__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocoremanagementbase.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocontribauthmanagementcommandscreatesuperuser.py", line 79, in execute
return super().execute(*args, **options)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocoremanagementbase.py", line 369, in execute
output = self.handle(*args, **options)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocontribauthmanagementcommandscreatesuperuser.py", line 189, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
File "C:Usersfreddyparcprojectsexam-masteraccountsmodels.py", line 21, in create_superuser
user = self.create_user(roll,phone,name,password=password)
File "C:Usersfreddyparcprojectsexam-masteraccountsmodels.py", line 16, in create_user
user.save(using=self._db)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocontribauthbase_user.py", line 66, in save
super().save(*args, **kwargs)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbmodelsbase.py", line 745, in save
self.save_base(using=using, force_insert=force_insert,
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbmodelsbase.py", line 782, in save_base
updated = self._save_table(
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbmodelsbase.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbmodelsbase.py", line 924, in _do_insert
return manager._insert(
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbmodelsmanager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbmodelsquery.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbmodelssqlcompiler.py", line 1391, in execute_sql
cursor.execute(sql, params)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbbackendsutils.py", line 100, in execute
return super().execute(sql, params)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbbackendsutils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbbackendsutils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbbackendsutils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbutils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbbackendsutils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:UsersfreddyparcAppDataLocalProgramsPythonPython38-32libsite-packagesdjangodbbackendssqlite3base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_user.course_id*

提前感谢。

您需要将课程字段添加到自定义用户模型的REQUIRED_FIELDS中:

class User(AbstractBaseUser):
phone= models.CharField(verbose_name='phone number', max_length=12,unique=True)
name=models.CharField(max_length=150,null=True)
roll=models.CharField(max_length=20,verbose_name='roll',unique=True)
course=models.ForeignKey(Course,on_delete=models.CASCADE)
date_joind=models.DateTimeField(verbose_name='date joind', auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff=models.BooleanField(default=False)
USERNAME_FIELD = 'roll'
REQUIRED_FIELDS = ['name','phone', 'course']
objects = UserManager()
def __str__(self):
return self.name
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True

您还需要更改您的自定义用户管理器:

class UserManager(BaseUserManager):
def create_user(self, phone, roll, course, password, name=None):
if isinstance(course, int):
course = Course.objects.get(pk=course)
user = self.model(phone=phone, roll=roll, course=course, name=name)
user.set_password(password)
user.save()
return user
def create_superuser(self, phone, roll, course, password, name=None):
user = self.create_user(phone=phone, roll=roll, course=course, password=password, name=name)
user.is_staff = True
user.is_admin = True
user.save()
return user

现在,当您运行命令python manage.py createsuperuser时,它要求您输入一个课程(您需要插入要关联的course实例的主键的值)

相关内容

  • 没有找到相关文章