在Django验证方法无回报 [英] Authentication method return None in django

查看:327
本文介绍了在Django验证方法无回报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我。当想要做的登录,认证方式登录回报没有一个视图中的Django做了一个简单的注册和登录页面。
我authentcate应用
models.py

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

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

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.It得到两个领域的数据,但验证方法返回无。
为此,我写 AUTH_USER_MODEL ='register.Consultants'在我的设置文件,则显示另一个错误 AttributeError的:对象类型顾问有没有属性 REQUIRED_FIELDS

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'

我怎样才能通过身份验证登录method.Why它不工作
请帮我在这

How can i get logged in by authenticate method.Why it is not working Please help me in this

推荐答案

您自定义的用户模型命名为 MYUSER 但是在配置您引用完全不同的 register.Consultants - 使用 MYUSER 模式

you have your custom user model named MyUser however in your configuration you reference totally different register.Consultants - use MyUser model.

这是我能看到的,每个用户将是一个顾问,那么为什么不来简化你所有的code,并创建模型类顾问将处理用户和个人资料信息:

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:


  • is_staff标志使用默认的管理员实施限制非超级用户访问管理;如果你想使用的任何的许可,例如这是很重要一些用户将无法编辑其他用户数据,或者你想删除的权利删除一些记录,他们中的一些,只有超级用户标志 - 每个用户都可以做的一切

  • 为什么你决定手动管理主键?这是不是唯一的坏code,但它可能会产生错误的时候会有在同一时间许多请求

  • 按照惯例,类名应该是单数 - 一个记录一个顾问

  • 如果你用一对单 - 使用它作为你的主键 - 只是为了简化code和有更好的理解还有什么

  • 如果您引用其他模型外键或者一个对一 - 你仍然引用整个模型不是它的属性格式,所以 USER_NAME = models.OneToOneField(MYUSER)应为用户= models.OneToOneField(MYUSER),所以那么这将是明显的,当你将访问 consultant_x.user.name

  • 我不知道为什么你已经把国家,州,市评为整场...加上MaxLengthValidator不会与整数整数办公室没有LEN()方法

  • 的日期 - 时间域,有 auto_now_add auto_now 标志 - 不过如此默认

  • is_staff flag is used by default admin implementation to limit access of non-superuser users to the admin; this is important if you would like to use any permission e.g. some users will not be able to edit other user data, or you want to remove right to delete some records for some of them, with only superuser flag - every user can do everything
  • why you had decided to manage primary key manually? this is not only bad code, but it may generate errors when there will be many requests at the same time
  • by convention, class names should be singular - one record is one Consultant
  • if you use one-to-one - use it as your primary key - just to simplify code and have better understanding what is there
  • if you reference other model as foreign key or one-to-one - you still reference whole model not it's propery, so 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
  • I do not know why you had put country, state and city as integer fields... plus MaxLengthValidator will not work with integers integers do not have len() method
  • for the date-time fields, there are auto_now_add and auto_now flags - much better than default

这篇关于在Django验证方法无回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆