首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Django:列"is_admin“中的空值违反了null约束。

Django:列"is_admin“中的空值违反了null约束。
EN

Stack Overflow用户
提问于 2019-09-29 06:57:59
回答 3查看 830关注 0票数 0

简单问题:为什么要得到这个错误:

代码语言:javascript
运行
复制
Integrity Error: null value in column "is_admin" violates not-null constraint

当我使用此代码创建一个用户时,

代码语言:javascript
运行
复制
# 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 -以下是详细信息.

代码语言:javascript
运行
复制
# 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']

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

代码语言:javascript
运行
复制
# 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)

要确定的是,这是追踪

代码语言:javascript
运行
复制
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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-09-29 08:21:05

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

票数 1
EN

Stack Overflow用户

发布于 2019-09-29 08:24:58

实际上,默认的Django用户模型(来源)中没有来源字段。

似乎数据库中的这个字段具有非空约束。

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

代码语言:javascript
运行
复制
python manage.py makemigrations api
python manage.py migrate api

如果没有帮助,请尝试从数据库中删除该列。如果你在使用postgres的话

代码语言:javascript
运行
复制
ALTER TABLE UserProfile 
DROP COLUMN is_admin;
票数 2
EN

Stack Overflow用户

发布于 2022-02-23 15:03:31

很可能,您已经应用了迁移,然后回滚更改(在某些版本控制系统中)。

重要:此时,更改已在代码中回滚,而不是在数据库表中回滚。

您需要做的是签出一个应用迁移的分支:

代码语言:javascript
运行
复制
git checkout <branch_name>

撤消此迁移:

代码语言:javascript
运行
复制
python manage.py migrate <app_name> <N-1>

下面是您最近一次迁移文件开始时的编号:<migration>-003

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58153022

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档