django admin扩展user表password验证及set_password

一般如果扩展了django user内置表,在admin后台创建新用户的时候密码将会变成明文,故而导致登录不成功。所以我们在admin.py可以通过form自定义进行对password进行操作,可以双重验证并且可以set_password将明文的密码修改成Hash加密过的密码。

from django.contrib import admin
from django.contrib.auth.models import AbstractUser
# Register your models here.
from user_profile.models import User,LoginLog
# admin.site.register(User)
admin.site.register(LoginLog)

from django.contrib.auth import (
    authenticate, get_user_model, password_validation,
)
from django.contrib.auth.forms import UsernameField

from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField

class UserCreationForm(forms.ModelForm):
    """
    A form that creates a user, with no privileges, from the given username and
    password.
    """
    error_messages = {
        'password_mismatch': "The two password fields didn't match.",
    }
    password1 = forms.CharField(
        label="Password",
        strip=False,
        widget=forms.PasswordInput,
    )
    password2 = forms.CharField(
        label="Password confirmation",
        widget=forms.PasswordInput,
        strip=False,
        help_text="Enter the same password as before, for verification.",
    )

    class Meta:
        model = User
        fields = ("username",)
        field_classes = {'username': UsernameField}

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        if self._meta.model.USERNAME_FIELD in self.fields:
            self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': ''})

    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(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        self.instance.username = self.cleaned_data.get('username')
        password_validation.validate_password(self.cleaned_data.get('password2'), self.instance)
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user
from django.contrib.auth.admin import UserAdmin as auth_UserAdmin
class UserAdmin(auth_UserAdmin):
    add_form = UserCreationForm

 

posted @ 2018-04-23 17:36  karina梅梅  阅读(4525)  评论(0编辑  收藏  举报