[Fixed]-Model inherited from AbstractUser doesn't hash password field

7👍

You need to define a function to hash that password. I think you directly save it to database.

class MyForm(forms.ModelForm):
    ............
    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(MyForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user

21👍

You don’t have to actually define your own function. You just need to use register it with the UserAdmin class from django.contrib.auth.admin and it works out of the box.

Explicitly, in your admin.py file make sure you have the following:

from django.contrib.auth.admin import UserAdmin
admin.site.register(CustomUserModel, UserAdmin)

If you have additional custom fields on your model, the above way of registering will make them not shown in the admin. In this case, you can make it work by making your custom Admin class inherit from the UserAdmin class, like the following:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

@admin.register(CustomUserModel)
class CustomUserModelAdmin(UserAdmin):
    ...

-1👍

Procedure djnago >=3.0

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

    YEAR_IN_SCHOOL_CHOICES = [('1', '1 class'),('2', '2 class'),('3', '3 class'),('4', '4 class'),('5', '5 class'),('6', '6 class'),('7', '7 class'),('8', '8 class'),('9', '9 class'),('10', '10th class'),]
    
    class User(AbstractUser):
        type = models.CharField(max_length=256, choices=(('1','Student'), ('2','Professor'), ('3','lower_staf')), default='1')  
    
    
    class Student(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True )
        gender = models.BooleanField(choices=((1,'Male'), (2,'Female'), (3,'Trans')), 
    
        def __str__(self):
            return '{}'.format(self.user)

admin.py

from django.contrib import admin
from.models import User, Student
from django.contrib.auth.admin import UserAdmin

class CustomUserAdmin(UserAdmin):

    fieldsets = UserAdmin.fieldsets + ((None, {'fields': ('type',)}),)
    add_fieldsets = UserAdmin.add_fieldsets + ((None, {'fields': ('type',)}),)

class Student_admin(admin.ModelAdmin):
    pass

admin.site.register(User, CustomUserAdmin)
admin.site.register(Student, Student_admin)

Leave a comment