简体   繁体   English

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

[英]Django: null value in column "is_admin" violates not-null constraint

Simple Question: Why do I get this error:简单问题:为什么会出现此错误:

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

When I Create a User with This Code?当我使用此代码创建用户时?

# views.py

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




The Error Sounds clear enough, except that I don't have a column called "is_admin" in my custom user model. I've tried specifying that "is_admin = False" in the code above and in the Customer user manager below, but when I do that, I get a new error that says 'is_admin' is an invalid keyword argument for this function - Here are the details...错误听起来很清楚,只是我的自定义用户 model 中没有名为“is_admin”的列。我尝试在上面的代码和下面的客户用户管理器中指定“is_admin = False”,但是当我这样做了,我收到一个新错误,指出'is_admin' is an invalid keyword argument for this function - 以下是详细信息...

# 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']

As a sanity check, here is my Customer user manager:作为完整性检查,这是我的客户用户经理:

# 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)

And just to be sure, here is the traceback可以肯定的是,这是回溯

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

As far as I know, in django there are some permission related fields in User model.据我所知,在 django 中,用户 model 中有一些权限相关的字段。 eg is_staff, is_admin, is_active, is_superuser.例如 is_staff、is_admin、is_active、is_superuser。 Since you are using your own custom model, you need to have these fields in model definition.由于您使用的是自己的自定义 model,因此您需要在 model 定义中包含这些字段。

Actually there is no is_admin field in default Django user models (source ).实际上默认 Django 用户模型中没有 is_admin 字段(来源)。

Seems like you have this field in the database with non-null constraint.似乎您在数据库中有此字段且具有非空约束。

To remove is_admin field try to run:要删除 is_admin 字段,请尝试运行:

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

If it didn't help try to drop this column from database.如果它没有帮助尝试从数据库中删除此列。 In case you're using postgres it would be something like如果您使用的是 postgres,它将类似于

ALTER TABLE UserProfile 
DROP COLUMN is_admin;

Most likely, you have applied a migration, and then rolled changes back (in some version control system).很可能,您已经应用了迁移,然后回滚了更改(在某些版本控制系统中)。

Important: at this point, changes have been rolled back in your code, but not in the database table.重要提示:此时,更改已在您的代码中回滚,但未在数据库表中回滚。

What you need to do is to checkout a branch, in which a migration was applied:您需要做的是检查一个分支,其中应用了迁移:

git checkout <branch_name>

Undo this migration:撤消此迁移:

python manage.py migrate <app_name> <N-1>

N here is the number at the start of your latest migrations file: <migration>-003 N 这是最新迁移文件开头的编号: <migration>-003

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

相关问题 Django - 列中的空值违反了 Django 管理中的非空约束 - Django - null value in column violates not-null constraint in Django Admin Django-“ imageLink”列中的空值违反了非空约束 - Django - Null value in column “imageLink” violates not-null constraint Django:关系的“id”列中的 null 值违反非空约束 - Django : null value in column "id" of relation violates not-null constraint “ user_id”列中的空值违反了非空约束 - null value in column “user_id” violates not-null constraint 保存ModelForm时,列中的null值违反非空约束 - null value in column violates not-null constraint while saving ModelForm “ city_id”列中的空值违反了非空约束 - null value in column “city_id” violates not-null constraint Flask SQLAlchemy null “id”列中的值违反非空约束 - Flask SQLAlchemy null value in column "id" violates not-null constraint “ job_id”列中的空值违反了非空约束 - null value in column “job_id” violates not-null constraint “ user_id”列中的null值违反了非null约束Django - null value in column “user_id” violates not-null constraint Django “ author_id”列中的Django IntegrityError空值违反了非空约束 - Django IntegrityError null value in column “author_id” violates not-null constraint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM