验证方法在django中返回None

时间:2016-04-26 09:36:06

标签: python django authentication

你好我在django做了一个简单的注册和登录页面。当想要登录时,登录视图里面的认证方法返回none。 我的authenticntcate应用程序 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)

当我尝试登录并sed密码和电子邮件id。它获取两个字段数据但验证方法返回None。 为此,我在我的设置文件中写了AUTH_USER_MODEL = 'register.Consultants',然后显示另一个显示AttributeError: type object 'Consultants' has no attribute 'REQUIRED_FIELDS'

的错误

如何通过身份验证方法登录。为什么它不起作用 请帮帮我

1 个答案:

答案 0 :(得分:0)

您拥有名为MyUser的自定义用户模型,但在您的配置中,您引用完全不同的register.Consultants - 使用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标志来限制非超级用户对admin的访问;如果您想使用任何权限,这一点很重要,例如:一些用户将无法编辑其他用户数据,或者您希望删除权限以删除其中一些用户的某些记录,只有超级用户标志 - 每个用户都可以执行所有操作
  • 为什么您决定手动管理主键?这不仅是错误的代码,而且当同时有许多请求时可能会产生错误
  • 按照惯例,类名应该是单数 - 一个记录是一个顾问
  • 如果您使用一对一 - 将其用作主键 - 只是为了简化代码并更好地理解其中的内容
  • 如果你引用其他模型作为外键或一对一 - 你仍然引用整个模型而不是它的属性,所以user_name = models.OneToOneField(MyUser)应该是user = models.OneToOneField(MyUser),那么它将是何时访问consultant_x.user.name
  • 我不知道为什么你把国家,州和城市作为整数字段...加上MaxLengthValidator不能用整数整数没有len()方法
  • 对于日期时间字段,有auto_now_addauto_now标记 - 比default
  • 好得多