![](/img/trans.png)
[英]“Invalid password format or unknown hashing algorithm.” Django - new user
[英]Password: Invalid password format or unknown hashing algorithm even after setting in the create user function
我有一個自定義的用戶模型:
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()
函數中,但未設置密碼。 我究竟做錯了什么?
在調用我的自定義模型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
管理員
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.