Authentication method return None in django
Hello I made a simple registration and login page in django .when want to do login, authentication method inside the view of login return none. my authentcate app models.py
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
admin.py
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)
when i try to login and sed password and email id.It gets both field data but authenticate method return None. For this i write AUTH_USER_MODEL = 'register.Consultants'
in my setting file, then another error showing AttributeError: type object 'Consultants' has no attribute 'REQUIRED_FIELDS'
How can i get logged in by authenticate method.Why it is not working Please help me in this
you have your custom user model named MyUser
however in your configuration you reference totally different register.Consultants
- use MyUser
model.
From what can I see, every user will be a Consultant, so why not to simplify all of your code and create one model class Consultants
which will handle user and profile information:
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
few, off-topic comments:
user_name = models.OneToOneField(MyUser)
should be user = models.OneToOneField(MyUser)
, so then it will be clear when you will access consultant_x.user.name
auto_now_add
and auto_now
flags - much better than default
下一篇: 身份验证方法在django中返回无