这是我的问题: 我想从shell验证自定义的AbstractBaseUser:
>>from django.contrib import auth
>>u = auth.authenticate(username = 'test@mejl.com', password = '123')
>>u == None
True
>>from userprofiles.models import MyUser
>> MyUser(email = 'new@hope.com', password = '321', date_of_birth='1999-9-9').save()
>>u = auth.authenticate(username = 'new@hope.com', password = '321')
>>u == None
True
>>u = auth.authenticate(email= 'new@hope.com', password = '321') #just to check
>>u == None
True
尝试从表单保存的用户(因为传递哈希),用户手动插入数据库,用户从shell创建并保存。
这是我的用户模型类:
from django.db import models
from django.utils.crypto import get_random_string
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser)
import string
import random
class MyUserManager(BaseUserManager):
def create_user(self, email, date_of_birth, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
date_of_birth=date_of_birth,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, date_of_birth, password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(email,
password=password,
date_of_birth=date_of_birth
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
date_of_birth = models.DateField()
role = models.CharField(max_length=15, default='guest')
confirmation_key = models.CharField(max_length=50,default = '/')
registration_confirmed = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['date_of_birth']
def is_guest(self):
if self.role == 'guest':
return True
return False
def is_restaurant_manager(self):
if self.role == 'restmanager':
return True
return False
def is_system_manager(self):
if self.role == 'sysmanager':
return True
return False
def get_role(self):
return self.role
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __str__(self): # __unicode__ on Python 2
return self.email
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
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
def set_reg_key(self, key):
self.confirmation_key = key
以下是我将其保存到db:
的视图def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
print "usao"
form.save()
print form.cleaned_data['email']
emailk = form.cleaned_data['email']
set_unique_reg_key(emailk)
return HttpResponseRedirect('/accounts/register1success')
else:
print "false je"
args = {}
args.update(csrf(request))
args['form']=UserCreationForm()
return render_to_response('userprofiles/register.html', args)
def set_unique_reg_key(emailk):
reg_key = ''.join(random.choice(string.ascii_uppercase) for i in range(12))
uu = MyUser.objects.filter(confirmation_key=reg_key)
if not uu:
try:
u = MyUser.objects.get(email=emailk)
except(KeyError, MyUser.DoesNotExist):
print
u.set_reg_key(reg_key)
print u.confirmation_key
u.save()
else:
set_unique_reg_key(emailk)
这是表格:
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,required=True)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput,required=True)
class Meta:
model = MyUser
fields = ('email', 'date_of_birth')
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
另外,我已经设置:
AUTH_PROFILE_MODULE = 'userprofiles.MyUser'
而且,如果我理解corectly authenticate应该适用于任何由AbstractBaseUser制作的模型。所以我没有制作CustomBackend。
答案 0 :(得分:1)
如果您使用的是Django 1.7或更高版本,我认为您应该使用AUTH_USER_MODEL
代替AUTH_PROFILE_MODULE
,因为它已根据this删除。
答案 1 :(得分:0)
您应用的名称是什么?
AUTH_USER_MODEL
的语法为app.model
。
您的问题可能与身份验证功能有关。这是我自己定制模型的功能。
def authenticate(self, username=None, password=None):
""" Authenticate a user based on email address as the user name. """
try:
user = UserAccount.objects.get(email=username)
if user.check_password(password):
return user
except UserAccount.DoesNotExist:
return None
然后,您再次发送电子邮件作为用户名进行身份验证...