Custom User model fields (AbstractUser) not showing in django admin

前端 未结 3 1801
独厮守ぢ
独厮守ぢ 2021-02-05 10:00

I have extended User model for django, using AbstractUser method. The problem is, my custom fields do not show in django admin panel.

My models.py:

from          


        
3条回答
  •  伪装坚强ぢ
    2021-02-05 10:40

    You have to override UserAdmin as well, if you want to see your custom fields. There is an example here in the documentation.

    You have to create the form for creating (and also changing) user data and override UserAdmin. Form for creating user would be:

    class UserCreationForm(forms.ModelForm):
        password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
        password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
    
        class Meta:
            model = User
            fields = '__all__'
    
        def clean_password2(self):
            password1 = self.cleaned_data.get("password1")
            password2 = self.cleaned_data.get("password2")
            if password1 and password2 and password1 != password2:
                raise forms.ValidationError("Passwords don't match")
            return password2
    
        def save(self, commit=True):
            user = super().save(commit=False)
            user.set_password(self.cleaned_data["password1"])
            if commit:
                user.save()
            return user
    

    You override UserAdmin with:

    from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
    
    class UserAdmin(BaseUserAdmin):
        add_form = UserCreationForm
        add_fieldsets = (
            (None, {
                'classes': ('wide',),
                'fields': ('email', 'first_name', 'last_name', 'is_bot_flag', 'password1', 'password2')}
            ),
        )
    

    and then you register:

    admin.site.register(User, UserAdmin)
    

    I pretty much copy/pasted this from documentation and deleted some code to make it shorter. Go to the documentation to see the full example, including example code for changing user data.

提交回复
热议问题