Django Admin Not Hashing Custom User Password

前端 未结 3 2085
情深已故
情深已故 2021-02-05 03:44
  • Python 3
  • Django 1.5
  • PostgreSQL 5.0.3

I\'m new to Django & I\'m making a Django app that makes use of AbstractUser, but when I create

相关标签:
3条回答
  • 2021-02-05 03:50

    I guess the problem is that you inherited ModelAdmin instead of UserAdmin from django.contrib.auth.admin in your admin.py.

    Sample code:

    from django.contrib.auth.admin import UserAdmin
    from .models import Employee
    
    class EmployeeAdmin(UserAdmin):
        pass
    
    admin.site.register(Employee, EmployeeAdmin)
    
    0 讨论(0)
  • 2021-02-05 03:56

    You can add the form code to the admin.py file. You will, however, also need to add the definition of the form class, not just the save() method and also the definition of the UserAdmin descended class. I think example will clarify:

    class UserCreationForm(forms.ModelForm):
        class Meta:
            model = CustomUser
            fields = ('email',)
    
        def save(self, commit=True):
            # Save the provided password in hashed format
            user = super(UserCreationForm, self).save(commit=False)
            user.set_password(self.cleaned_data["password"])
            if commit:
                user.save()
            return user
    
    
    class CustomUserAdmin(UserAdmin):
        # The forms to add and change user instances
        add_form = UserCreationForm
        list_display = ("email",)
        ordering = ("email",)
    
        fieldsets = (
            (None, {'fields': ('email', 'password', 'first_name', 'last_name')}),
            )
        add_fieldsets = (
            (None, {
                'classes': ('wide',),
                'fields': ('email', 'password', 'first_name', 'last_name', 'is_superuser', 'is_staff', 'is_active')}
                ),
            )
    
        filter_horizontal = ()
    
        admin.site.register(CustomUser, CustomUserAdmin)
    

    This should get you started. You will need to customize the classes's fields to match the fields of your user class.

    More info is here: https://docs.djangoproject.com/en/dev/topics/auth/customizing/

    0 讨论(0)
  • 2021-02-05 04:09

    Because it directly save in the database. So before it save you must override the method for hashing the password. Add this in your form:

    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
    
    0 讨论(0)
提交回复
热议问题