Django custom user model in admin, relation “auth_user” does not exist

前端 未结 5 1833
小鲜肉
小鲜肉 2020-12-13 15:46

I have a custom user model as below:

class User(AbstractUser):
    subscribe_newsletters = models.BooleanField(default=True)
    old_id = models.IntegerField         


        
5条回答
  •  忘掉有多难
    2020-12-13 16:39

    After some digging around I found this

    https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#custom-users-and-the-built-in-auth-forms

    The culprit is a function clean_username inside UserCreationForm inside django.contrib.auth.forms.py. A few tickets have been created, but apparently the maintainers don't think it's a defect:

    https://code.djangoproject.com/ticket/20188

    https://code.djangoproject.com/ticket/20086

    def clean_username(self):
            # Since User.username is unique, this check is redundant,
            # but it sets a nicer error message than the ORM. See #13147.
            username = self.cleaned_data["username"]
            try:
                User._default_manager.get(username=username)
            except User.DoesNotExist:
                return username
            raise forms.ValidationError(self.error_messages['duplicate_username'])
    

    The User in this file is directly referencing to the builtin user model.

    To fix it, I created my custom forms

    from models import User #you can use get_user_model
    from django.contrib.auth.forms import UserCreationForm
    from django.contrib.auth.admin import UserAdmin
    from django.contrib.auth import forms
    
    class MyUserCreationForm(UserCreationForm):
        def clean_username(self):
            # Since User.username is unique, this check is redundant,
            # but it sets a nicer error message than the ORM. See #13147.
            username = self.cleaned_data["username"]
            try:
                User._default_manager.get(username=username)
            except User.DoesNotExist:
                return username
            raise forms.ValidationError(self.error_messages['duplicate_username'])
    
        class Meta(UserCreationForm.Meta):
            model = User
    
    class MyUserAdmin(UserAdmin):  
        add_form = MyUserCreationForm   
    
    admin.site.register(User,MyUserAdmin)
    

    Or you can try monkey patching the original UserCreationForm to replace the User variable.

提交回复
热议问题