Django管理员不哈希自定义用户密码

Zam*_*tta 18 django python-3.x

  • Python 3
  • Django 1.5
  • PostgreSQL 5.0.3

我是Django的新手,我正在制作一个使用AbstractUser的Django应用程序,但是当我在Django管理员中创建用户,然后在管理员中查看用户的信息时,我会以纯文本形式看到密码.直接在DB中检查,我看到密码肯定是以明文形式存储的.

我正在尝试编写一些视图来进行一些身份验证,但即使用户名和密码正确也无法正常工作.所以我猜这个authenticate()函数是哈希但是返回,None因为密码实际上没有哈希.

是否有任何可能的原因导致密码没有被哈希?

我发布了一些代码,但我不认为任何代码会有所帮助,因为我的模型不包含任何与密码字段有关的代码(由Django生成和完成).如果我正在做或不做什么,我甚至不知道它的代码部分是什么,所以我必须从我的设置,模型,管理员等发布所有内容.

Daw*_*ian 15

我想问题是你在admin.py中从django.contrib.auth.admin继承了ModelAdmin而不是UserAdmin.

示例代码:

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

class EmployeeAdmin(UserAdmin):
    pass

admin.site.register(Employee, EmployeeAdmin)
Run Code Online (Sandbox Code Playgroud)


pko*_*out 10

您可以将表单代码添加到admin.py文件中.但是,您还需要添加表单类的定义,而不仅仅是save()方法以及UserAdmin后继类的定义.我想这个例子将澄清:

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)
Run Code Online (Sandbox Code Playgroud)

这应该让你开始.您需要自定义类的字段以匹配用户类的字段.

更多信息请访问:https://docs.djangoproject.com/en/dev/topics/auth/customizing/


cat*_*ine 0

因为它直接保存在数据库中。因此,在保存之前,您必须覆盖对密码进行哈希处理的方法。将其添加到您的表单中:

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
Run Code Online (Sandbox Code Playgroud)

  • 我还没有制作任何表单(我正在使用 Django 管理员生成的表单),所以我不太明白我的表单在哪里。我要把它放在我的 admin.py 中吗? (3认同)