2

The problem is i need an extra field to add my Django usermodel via a custom user model called 'is_admin'

so ,this is the code i added to model

class CustomUser(AbstractUser):
    is_admin = models.BooleanField(default=False)

but i registered this model to admin.py

when i tried to add a user using django admin page the password stores as plain not hashing hos to solve this problem

AUTH_USER_MODEL = 'cAdmin.CustomUser'

i've already changed the default user model

and

admin.py


from django.contrib import admin
from .models import CustomUser,Priority
from django import forms
from django.contrib.auth.admin import UserAdmin
# Register your models here.

admin.site.register(CustomUser)
admin.site.register(Priority)

1 Answers1

0

The ModelAdmin will by default use a vanilla ModelForm, and that will indeed not hash the password.

We can however easily work with a UserCreationForm and UserChangeForm which will then use .set_password instead:

from django.contrib.auth.forms import UserChangeForm, UserCreationForm


@admin.register(CustomUser)
class CustomUserAdmin(admin.ModelAdmin):
    form = UserChangeForm
    add_form = UserCreationForm

Indeed, if we look at the source code of the BaseUserCreationForm [GitHub], we see:

def save(self, commit=True):
    user = super().save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()
        if hasattr(self, "save_m2m"):
            self.save_m2m()
    return user
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555