Django:“ is_admin”列中的空值违反了非空约束

时间:2019-09-29 06:57:59

标签: python django authentication django-models

简单问题:为什么会出现此错误:

Integrity Error: null value in column "is_admin" violates not-null constraint

我使用此代码创建用户吗?

# views.py

user_obj = UserProfile.objects.create_user(
    username    = 'username',
    email       = 'test@example.com',
    password    = 'password',
)




错误听起来很清楚,除了我的自定义用户模型中没有名为“ is_admin”的列。我尝试在上面的代码和下面的客户用户管理器中指定“ is_admin = False”,但是当我这样做时,我收到一个新错误,提示'is_admin' is an invalid keyword argument for this function-以下是详细信息... < / p>

# models.py

### My Custom User Model Extending AbstractBaseUser
class UserProfile(AbstractBaseUser, PermissionsMixin):
    email      = models.EmailField(max_length=255, unique=True)
    username   = models.CharField(max_length=255, unique=True)
    # ... other stuff [definitely nothing called "is_admin"]
    is_active  = models.BooleanField(default=True)
    is_staff   = models.BooleanField(default=False)
    is_editor  = models.BooleanField(default=False)

    objects = UserProfileManager()

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

作为健全性检查,这是我的客户用户经理:

# models.py

class UserProfileManager(BaseUserManager):
    def _create_user(self, username, email, password, **extra_fields):
        if not username:
            raise ValueError('The given username must be set')
        email       = self.normalize_email(email)
        username    = self.model.normalize_username(username)
        user        = self.model(username=username, email=email, **extra_fields)

        # user      = self.model(username=username, email=email, is_admin = False, **extra_fields) ### I tried this, but I get the alternate error described in the paragraph above
        user.is_admin = False ### I added this in as a remedy. but I get the same error in the Title of this post

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

    def create_user(self, username, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        extra_fields.setdefault('is_staff', False)
        return self._create_user(username, email, password, **extra_fields)

并且可以肯定的是,这是回溯

Traceback (most recent call last):
  File "C:\Users\myuser\MyApp\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request)
  File "C:\Users\myuser\MyApp\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request)
  File "C:\Users\myuser\MyApp\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\myuser\MyApp\MyApp\api\views.py", line 235, in cast_creator user_obj = create_user_with_just_an_email(email)
  File "C:\Users\myuser\MyApp\MyApp\authenticate\views.py", line 316, in create_user_with_just_an_email password    = password,
  File "C:\Users\myuser\MyApp\MyApp\api\models.py", line 28, in create_user return self._create_user(username, email, password, **extra_fields)
  File "C:\Users\myuser\MyApp\MyApp\api\models.py", line 22, in _create_user user.save(using=self._db)
  File "C:\Users\myuser\MyApp\lib\site-packages\django\contrib\auth\base_user.py", line 73, in save super().save(*args, **kwargs)
  File "C:\Users\myuser\MyApp\lib\site-packages\django\db\models\base.py", line 718, in save force_update=force_update, update_fields=update_fields)
  File "C:\Users\myuser\MyApp\lib\site-packages\django\db\models\base.py", line 748, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "C:\Users\myuser\MyApp\lib\site-packages\django\db\models\base.py", line 831, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "C:\Users\myuser\MyApp\lib\site-packages\django\db\models\base.py", line 869, in _do_insertusing=using, raw=raw)
  File "C:\Users\myuser\MyApp\lib\site-packages\django\db\models\manager.py", line 82, in manager_metho return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\myuser\MyApp\lib\site-packages\django\db\models\query.py", line 1136, in _inser return query.get_compiler(using=using).execute_sql(return_id)
  File "C:\Users\myuser\MyApp\lib\site-packages\django\db\models\sql\compiler.py", line 1289, in execute_sq cursor.execute(sql, params)
  File "C:\Users\myuser\MyApp\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params)
  File "C:\Users\myuser\MyApp\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\myuser\MyApp\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context)
  File "C:\Users\myuser\MyApp\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params)
  File "C:\Users\myuser\MyApp\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\myuser\MyApp\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: null value in column "is_admin" violates not-null constraint

2 个答案:

答案 0 :(得分:1)

据我所知,在Django中,用户模型中有一些与权限相关的字段。例如is_staff,is_admin,is_active,is_superuser。由于您使用的是自己的自定义模型,因此需要在模型定义中包含这些字段。

答案 1 :(得分:1)

实际上,默认Django用户模型(source)中没有is_admin字段。

似乎您在数据库中具有非null约束的此字段。

要删除is_admin字段,请尝试运行:

python manage.py makemigrations api
python manage.py migrate api

如果没有帮助,请尝试从数据库中删除此列。如果您使用的是postgres,则可能是

ALTER TABLE UserProfile 
DROP COLUMN is_admin;