2016-04-26 63 views
1

你好我在django中做了一個簡單的註冊和登錄頁面。當想做登錄時,身份驗證方法裏面的登錄視圖返回none。 我authentcate應用 models.py身份驗證方法return在django中沒有

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.It得到兩字段數據但驗證方法返回無。 爲此,我在我的設置文件寫AUTH_USER_MODEL = 'register.Consultants',那麼另一個錯誤顯示AttributeError: type object 'Consultants' has no attribute 'REQUIRED_FIELDS'

?我怎樣才能通過method.Why它不工作 身份驗證登陸,請幫我在這

+0

你嘗試加入REQUIRED_FIELDS該模型更好? –

+0

如果我的身份驗證將通過添加所需的文件完成,那麼我一定會添加所需的文件 –

+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 

少,關-topic評論:

  • is_staff標誌默認使用管理員實現來限制非超級用戶訪問管理員;如果您想要使用的任何權限,則這一點很重要。有些用戶將無法編輯其他用戶數據,或者您想刪除某些記錄的權限,只有超級用戶標誌 - 每個用戶都可以做任何事情
  • 爲什麼您決定手動管理主鍵?這不僅是錯誤的代碼,但它可能會產生錯誤,當同時會有很多請求
  • 按照慣例,類名稱應該是單數 - 一個記錄是一個顧問
  • 如果您使用一對一 - 使用它作爲你的主鍵 - 只是爲了簡化代碼,並有更好的理解有什麼
  • 如果你引用其他模型作爲外鍵或一對一 - 你仍然參考整個模型不是它propery,所以user_name = models.OneToOneField(MyUser)應該是user = models.OneToOneField(MyUser),那麼你會清楚什麼時候你會訪問consultant_x.user.name
  • 我不知道你爲什麼把國家,州和城市作爲整數字段......加上MaxLengthValidator會不是整數整數辦公室沒有LEN()方法
  • 的日期 - 時間域,有auto_now_addauto_now標誌 - 比default