密码:即使在创建用户功能中设置后,密码格式或未知散列算法也无效

时间:2016-07-23 05:28:08

标签: python django django-models django-forms django-admin

我有自定义用户模型:

class CustomUserManager(BaseUserManager):
    def _create_user(self, email, username, password, first_name, last_name, date_of_birth, gender, mobile_number,
                     is_active, is_admin, is_superuser):
        if not email:
            raise ValueError('Email must be set')
        email = self.normalize_email(email)
        now = timezone.now()
        user = self.model(
            email=email,
            username=email,
            first_name=first_name,
            last_name=last_name,
            date_of_birth=date_of_birth,
            gender=gender,
            mobile_number=mobile_number,
            date_joined=now,
            is_active=is_active,
            is_admin=is_admin,
            is_superuser=is_superuser,
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, username, password, first_name, last_name, date_of_birth, gender, mobile_number,
                    **extra_fields):
        user = self._create_user(
            email,
            username,
            password,
            first_name,
            last_name,
            date_of_birth,
            gender,
            mobile_number,
            True,
            False,
            False,
            **extra_fields
        )
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, password, first_name, last_name, date_of_birth, gender, mobile_number,
                         **extra_fields):
        user = self._create_user(
            email,
            username,
            password,
            first_name,
            last_name,
            date_of_birth,
            gender,
            mobile_number,
            True,
            True,
            True,
            **extra_fields
        )
        user.save(using=self._db)
        return user

GENDERTYPE = (
    ('1', 'Male'),
    ('2', 'Female'),
    ('3', 'Other')
)

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), max_length=254, unique=True)
    username = models.CharField(_('user name'), max_length=254, unique=True)
    first_name = models.CharField(_('first name'), max_length=30)
    last_name = models.CharField(_('last name'), max_length=30)
    date_of_birth = models.DateField()
    gender = models.CharField(choices=GENDERTYPE, max_length=1)
    mobile_number = models.IntegerField(unique=True)
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = CustomUserManager()
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'date_of_birth', 'gender', 'mobile_number']

要处理的表格:

class UserCreationForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = ('email', 'username', 'first_name', 'last_name', 'date_of_birth', 'gender', 'mobile_number')


class UserChangeForm(forms.ModelForm):
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = CustomUser
        fields = (
            'email', 'username', 'first_name', 'last_name', 'date_of_birth', 'gender', 'mobile_number', 'is_active',
            'is_admin'
        )

    def clean_password(self):
        return self.initial["password"]

我可以毫无问题地保存新用户。

但是,当我尝试使用用户凭据登录时,我未经过身份验证。另外,在查看密码时,我会在管理界面中收到错误。

  

密码:无效的密码格式或未知的散列算法。

Admins.py:

class CustomUserAdmin(UserAdmin):
    form = UserChangeForm
    add_form = UserCreationForm
    list_display = ('first_name', 'last_name', 'email', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': (
            'email',
            'password'
        )}),
        ('Personal info', {'fields': (
            ('first_name', 'last_name'),
            'username',
            'date_of_birth',
            'gender',
            'mobile_number'
        )}),
        ('Permissions', {'fields': (
            'is_active',
            'is_admin'
        )}),
    )
    add_fieldsets = (
        (None, {'fields': (
            'email',
            'password'
        )}),
        ('Personal info', {'fields': (
            ('first_name', 'last_name'),
            'username',
            'date_of_birth',
            'gender',
            'mobile_number'
        )}),
    )
    search_fields = ('first_name', 'last_name', 'email',)
    ordering = ('first_name', 'email',)
    filter_horizontal = ()
admin.site.register(CustomUser, CustomUserAdmin)

虽然我使用密码将其保存在def _create_user()函数中,但未设置密码。我做错了什么?

1 个答案:

答案 0 :(得分:0)

我在调用自定义模型Account的创建方法时遇到了同样的问题,Account.objects.create( username='demo',email='demo12@demo.com', password='prakashsharma24#')

我刚刚使用 create_user 方法并将结果

Account.objects.create_user(username='abcdef',email='abcdef@demo.com',password='prakashsharma24#')

这是我的工作代码:

<强> models.py

from __future__ import unicode_literals

from django.db import models

from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
from django.db import models
class AccountManager(BaseUserManager):
def create_user(self, email, date_of_birth=None,password=None, **kwargs):
    print email, date_of_birth ,password,kwargs
    if not email:
        raise ValueError('Users must have a valid email address.')

    if not kwargs.get('username'):
        raise ValueError('Users must have a valid username.')

    account = self.model(
        email=self.normalize_email(email), username=kwargs.get('username'),
        date_of_birth=date_of_birth,
    )

    account.set_password(password)
    user.save(using=self._db)
    account.save()
    # user.save(using=self._db)

    return account
    # user = Account.objects.create_user(username='admin', 'webkul.com', 'adminpassword')
def create_superuser(self, email, date_of_birth,password, **kwargs):
    account = self.create_user(email,date_of_birth, password, **kwargs)

    account.is_admin = True
    account.is_staff = True

    account.save(using=self._db)

    return account

class Account(AbstractBaseUser):
email = models.EmailField(verbose_name='email address',
                    max_length=255,unique=True)
date_of_birth = models.DateField(null=True)

username = models.CharField(max_length=40, unique=True)

first_name = models.CharField(max_length=40, blank=True)
last_name = models.CharField(max_length=40, blank=True)
tagline = models.CharField(max_length=140, blank=True)
street = models.CharField(max_length=100, blank=True)
street1 = models.CharField(max_length=100, blank=True)
phone = models.CharField(max_length=40, blank=True)
website = models.CharField(max_length=40, blank=True)
city = models.CharField(max_length=40, blank=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

objects = AccountManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username','date_of_birth']

def __unicode__(self):
    return self.email

def get_full_name(self):
    return ' '.join([self.first_name, self.last_name])

def get_short_name(self):
    return self.first_name


def has_perm(self, perm, obj=None):
    "Does the user have a specific permission?"
    # Simplest possible answer: Yes, always
    return True

def has_module_perms(self, app_label):
    "Does the user have permissions to view the app `app_label`?"
    # Simplest possible answer: Yes, always
    return True

<强> admin.py

from django.contrib import admin

# Register your models here.
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from authentication.models import Account
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

class Meta:
    model = Account
    fields = ('email', 'date_of_birth','password')

def clean_password2(self):
    # Check that the two password entries match
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError("Passwords don't match")
    return password2

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["password1"])
    if commit:
        user.save()
    return user


class UserChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()

class Meta:
    model = Account
    fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin')

def clean_password(self):
    # Regardless of what the user provides, return the initial value.
    # This is done here, rather than on the field, because the
    # field does not have access to the initial value
    return self.initial["password"]


class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm

# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'date_of_birth', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
    (None, {'fields': ('email', 'password')}),
    ('Personal info', {'fields': ('date_of_birth',)}),
    ('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
    (None, {
        'classes': ('wide',),
        'fields': ('email', 'date_of_birth', 'password1', 'password2')}
    ),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()


admin.site.register(Account, UserAdmin)
admin.site.unregister(Group)