为超级用户的用户排除某些字段

时间:2019-06-17 11:05:44

标签: python python-3.x django-2.2

我正在尝试创建自定义用户模型,并具有诸如出生日期,当前级别和其他此类参数的参数。当我运行python manage.py createsuperuser时,出现错误,表明这些值不能为null。我不希望超级用户帐户使用这些参数。我该怎么办?

我尝试将以下行添加到从UserAdmin类继承的类中 exclude =('date_of_birth','currentLevel','totalStars','badges')

这是模型字段

class Learner(AbstractBaseUser):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    email = models.EmailField(max_length=255, unique=True)
    date_of_birth = models.DateField(auto_now=False, auto_now_add=False)

    currentLevel = models.ForeignKey(SubLevelConcepts, related_name='currentLevel', on_delete=models.CASCADE)
    totalStars = models.IntegerField(default=0)
    badges = models.IntegerField(default=0)

    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False)
    superuser = models.BooleanField(default=False)

    objects = LearnerManager()

这是管理类

class LearnerAdmin(UserAdmin):

    add_form = LearnerCreationForm
    form = LearnerChangeForm

    model = Learner

    exclude = ('date_of_birth', 'currentLevel', 'totalStars', 'badges')

    list_display = (
        'first_name',
        'last_name',
        'email',
        'staff',
        'active'
        )
    list_filter = (
        'email',
        'active'
    )
    fieldsets = (
        (None, {'fields': ('email', 'password',)}),
        ('Permissions', {'fields': ('staff', 'active')}),
    )

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'first_name', 'last_name','password1', 'passsword2', 'staff', 'active')}
        )
    )

    search_fields = ('email',)
    ordering = ('id',)
    filter_horizontal = ()

这是我运行python manage.py createsuperuser

时的最终错误
django.db.utils.IntegrityError: (1048, "Column 'currentLevel_id' cannot be null")

我希望超级用户只需输入电子邮件和密码即可完成工作。稍后再添加名字和姓氏

1 个答案:

答案 0 :(得分:0)

在您的null=True字段中添加default=NoneForeignKey,因此不是必需的,即

class Learner(AbstractBaseUser):
    # ...
    currentLevel = models.ForeignKey(SubLevelConcepts, null=True, related_name='currentLevel', on_delete=models.CASCADE)

您可能还想使用models.PROTECTmodels.SET_NULL而不是models.CASCADE-除非您确实希望在删除与用户匹配的SubLevelConcept后删除用户帐户,那是...

您可能还需要检查blank=True models field option FWIW。