Python django中的身份验证方法返回None
您好,我在django中创建了一个简单的注册和登录页面。当需要登录时,登录视图中的身份验证方法返回none。 我的authentcate应用程序 models.pyPython django中的身份验证方法返回None,python,django,authentication,Python,Django,Authentication,您好,我在django中创建了一个简单的注册和登录页面。当需要登录时,登录视图中的身份验证方法返回none。 我的authentcate应用程序 models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_us
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
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,
)
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.CharField(max_length=20)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
# REQUIRED_FIELDS = ['date_of_birth']
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 __unicode__(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
管理员
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 .models import MyUser
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 = MyUser
fields = ('email',)
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 = MyUser
fields = ('email', 'password', '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', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('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', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# Now register the new UserAdmin...
admin.site.register(MyUser, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
**login app**
models.py
from __future__ import unicode_literals
from datetime import datetime
from django.db import models
from django import forms
from django.core.validators import MaxValueValidator
from django.core.validators import MaxLengthValidator
from django.db.models import Max
from authenticationUser.models import MyUser
# from django.contrib.auth.models import User
# from django.contrib.auth.models import AbstractUser
# from django.contrib.auth.models import (AbstractBaseUser,
# PermissionsMixin,
# UserManager)
# # Create your models here.
class Consultants(models.Model):
# user=models.OneToOneField(User)
user_name= models.OneToOneField(MyUser)
consul_id=models.IntegerField(default=0,primary_key=True)
first_name=models.CharField(max_length=255,blank=True,null=True)
last_name=models.CharField(max_length=255,blank=True,null=True)
# email=models.EmailField(max_length=255,blank=True,null=True)
username=models.CharField(max_length=255,blank=True,null=True)
# password=models.CharField(max_length=50,blank=True,null=True)
consul_pic=models.ImageField(upload_to="/homeDocuments/pro//Registration/consul_pic",blank=True,null=True)
mobile_no=models.CharField(max_length=255,blank=True,null=True)
country=models.IntegerField(validators=[MaxLengthValidator(11)],blank=True,null=True)
state=models.IntegerField(validators=[MaxLengthValidator(11)],blank=True,null=True)
city=models.IntegerField(validators=[MaxLengthValidator(11)],blank=True,null=True)
experience=models.IntegerField(default=0,blank=True,null=True)
skills=models.CharField(max_length=255,blank=True,null=True)
education=models.CharField(max_length=255,blank=True,null=True)
linkedin_id=models.CharField(max_length=255,blank=True,null=True)
cteated_on=models.DateTimeField(default=datetime.now,blank=True,null=True)
last_upadted_on=models.DateTimeField(default=datetime.now,blank=True,null=True)
last_login=models.DateTimeField(default=datetime.now,blank=True,null=True)
is_active=models.BooleanField(default=False)
# objects = UserManager()
def __str__(self):
return self.first_name or u''
def save(self, *args, **kwargs):
# print "consul id",consul_id
consul_id=int(self.consul_id)
if consul_id==0:
queryset=Consultants.objects.all()
temp_id=queryset.aggregate(Max('consul_id'))
print "second print",temp_id
temp_id=temp_id.get('consul_id__max')
print "third print",temp_id
consul_id=""
if not temp_id:
consul_id="1"
else:
# int_consul= int(consul_id)
consul_id=int(temp_id)+1
self.consul_id=consul_id
super(Consultants, self).save(*args, **kwargs)
views.py
def login_user(request):
context = RequestContext(request)
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
print type(username)
# print "username",username
try:
print "username=========>",username
print "password========>",password
# user = Consultants.objects.get(Q(username= username) & Q(password= password))
# obj=Consultants.objects.filter()
# json = {"first_name":user.first_name,"email":user.email}
# def form_valid(self, form):
user=authenticate(email=username,password=password)
# user = authenticate(Q(username= username) , Q(password= password))
# user = authenticate(username=username, password=password)
print 'chala',user
if user.is_active:
# user.backend = 'django.contrib.auth.backends.ModelBackend'
# a=
print 'user',user
login(request, user)
# a= request.user.username
# print "abbabbaba",a
return render(request, 'success.html', json)
# return HttpResponse("welcome......you are succesfuly log in")
else:
return HttpResponse("Your account is disabled.")
except ObjectDoesNotExist:
return HttpResponse("INvalid User")
else:
return render_to_response('login.html', context)
当我尝试登录时,sed密码和电子邮件id。它获取两个字段数据,但authenticate方法不返回任何数据。
为此,我在设置文件中写入了AUTH\u USER\u MODEL='register.Consultants'
,然后出现另一个错误,显示AttributeError:type对象“Consultants”没有属性“REQUIRED\u FIELDS”
如何通过身份验证方法登录。为什么它不起作用
请在这方面帮助我您有名为
MyUser
的自定义用户模型,但是在您的配置中,您引用了完全不同的注册。顾问
-使用MyUser
模型
从我可以看到的情况来看,每个用户都是顾问,所以为什么不简化所有代码并创建一个模型类Consultants
,它将处理用户和配置文件信息:
class Consultant(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255, blank=True, null=True)
username = models.CharField(max_length=255, blank=True, null=True)
consul_pic = models.ImageField(upload_to="/homeDocuments/pro//Registration/consul_pic", blank=True, null=True)
mobile_no = models.CharField(max_length=255, blank=True, null=True)
country = models.IntegerField(validators=[MaxLengthValidator(11)], blank=True, null=True)
state = models.IntegerField(validators=[MaxLengthValidator(11)], blank=True, null=True)
city = models.IntegerField(validators=[MaxLengthValidator(11)], blank=True, null=True)
experience = models.IntegerField(default=0, blank=True, null=True)
skills = models.CharField(max_length=255, blank=True, null=True)
education = models.CharField(max_length=255, blank=True, null=True)
linkedin_id = models.CharField(max_length=255, blank=True, null=True)
created_on = models.DateTimeField(auto_now_add=True, blank=True, null=True)
last_updated_on = models.DateTimeField(auto_now=True, blank=True, null=True)
last_login = models.DateTimeField(auto_now_add=True, blank=True, null=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
# REQUIRED_FIELDS = ['date_of_birth']
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 __unicode__(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
很少有离题评论:
- is_staff标志在默认管理员实现中用于限制非超级用户对管理员的访问;如果您希望使用任何权限,例如某些用户将无法编辑其他用户数据,或者您希望删除其中某些用户的某些记录的权限(仅使用超级用户标志),则这一点非常重要-每个用户都可以做任何事
- 为什么决定手动管理主键?这不仅是错误的代码,而且在同时有多个请求时可能会产生错误
- 按照惯例,类名应该是单数的——一个记录就是一个顾问
- 如果您使用一对一-将其用作主键-只是为了简化代码并更好地理解其中的内容
- 如果您引用其他模型作为外键或一对一-您仍然引用整个模型,而不是它的属性,因此
应该是user\u name=models.OneToOneField(MyUser)
,这样您访问user=models.OneToOneField(MyUser)
consultant\u x.user.name
- 我不知道你为什么把国家、州和城市作为整型字段。。。加上MaxLengthValidator将无法处理整数整数没有len()方法
- 对于日期时间字段,有
和auto\u now\u add
标志-比auto\u now
default
必填字段=['出生日期]
。你需要有那个领域。