Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 自定义用户模型的django身份验证不起作用_Python_Django_Authentication - Fatal编程技术网

Python 自定义用户模型的django身份验证不起作用

Python 自定义用户模型的django身份验证不起作用,python,django,authentication,Python,Django,Authentication,我的问题是: 我正在尝试从shell对自定义AbstractBaseUser进行身份验证: >>from django.contrib import auth >>u = auth.authenticate(username = 'test@mejl.com', password = '123') >>u == None True >>from userprofiles.models import MyUser >> MyUser(em

我的问题是: 我正在尝试从shell对自定义AbstractBaseUser进行身份验证:

>>from django.contrib import auth
>>u = auth.authenticate(username = 'test@mejl.com', password = '123')
>>u == None
True
>>from userprofiles.models import MyUser
>> MyUser(email = 'new@hope.com', password = '321', date_of_birth='1999-9-9').save()
>>u = auth.authenticate(username = 'new@hope.com', password = '321')
>>u == None
True
>>u = auth.authenticate(email= 'new@hope.com', password = '321') #just to check
>>u == None
True
尝试使用从表单保存的用户(由于传递散列),手动插入数据库的用户,以及从shell生成和保存的用户

以下是我的用户模型类:

from django.db import models
from django.utils.crypto import get_random_string
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser)
import string
import random


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,
                            date_of_birth=date_of_birth
                            )
      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.DateField()
    role = models.CharField(max_length=15, default='guest')
    confirmation_key = models.CharField(max_length=50,default = '/')
    registration_confirmed = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['date_of_birth']

def is_guest(self):
    if self.role == 'guest':
        return True
    return False

def is_restaurant_manager(self):
    if self.role == 'restmanager':
        return True
    return False

def is_system_manager(self):
    if self.role == 'sysmanager':
        return True
    return False

def get_role(self):
    return self.role

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 __str__(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

def set_reg_key(self, key):
    self.confirmation_key = key
以下是我将其保存到db的视图:

def register_user(request):
if request.method == 'POST':
    form = UserCreationForm(request.POST)
    if form.is_valid():
        print "usao"
        form.save()

        print form.cleaned_data['email']
        emailk = form.cleaned_data['email']
        set_unique_reg_key(emailk)
        return HttpResponseRedirect('/accounts/register1success')
    else:
        print "false je"

args = {}
args.update(csrf(request))
args['form']=UserCreationForm()
return render_to_response('userprofiles/register.html', args)


def set_unique_reg_key(emailk):
    reg_key = ''.join(random.choice(string.ascii_uppercase) for i in range(12))
    uu = MyUser.objects.filter(confirmation_key=reg_key)
    if not uu:
        try:
            u = MyUser.objects.get(email=emailk)
        except(KeyError, MyUser.DoesNotExist):
            print

        u.set_reg_key(reg_key)
        print u.confirmation_key
        u.save()
    else:
        set_unique_reg_key(emailk)
以下是表格:

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,required=True)
password2 = forms.CharField(label='Password confirmation',     widget=forms.PasswordInput,required=True)

class Meta:
    model = MyUser
    fields = ('email', 'date_of_birth')

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
此外,我已设定:

AUTH_PROFILE_MODULE = 'userprofiles.MyUser'

而且,如果我理解正确,身份验证应该适用于任何由AbstractBaseUser制作的模型。因此我没有制作CustomBackend。

我认为如果您使用Django 1.7或更高版本,您应该使用
AUTH\u USER\u model
而不是
AUTH\u PROFILE\u MODULE
,因为它是根据删除的。

您的应用程序的名称是什么?
AUTH\u USER\u MODEL
的语法是
app.MODEL

您的问题可能与authenticate函数有关。这是我自己定制模型中的函数

def authenticate(self, username=None, password=None):
        """ Authenticate a user based on email address as the user name. """
        try:
            user = UserAccount.objects.get(email=username)
            if user.check_password(password):
                return user
        except UserAccount.DoesNotExist:
            return None

然后,您再次将电子邮件作为用户名发送以进行身份验证…

尝试过,但没有更改..我认为这不是问题所在,因为此设置来自django doc,标记为“Documentation version:1.8”。无论如何,谢谢。:)我的错误是,1.8中的AUTH_USER_模型..但仍然不起作用这是正确的答案,我打开Debugger,看到get_USER_MODEL()返回django的用户..然后我检查了我的设置,而不是AUTH_USER_模型,我编写了AUTH_USER_模块..两天之后发现了这样的错误:@问题可能是你没有使用后端。这是我自己的自定义模型的身份验证函数(在我的anwser中),我可以编写自己的函数来简单地检查数据库中是否有用户。但是,让来自AbstractBaseUser的自定义用户代替django的用户不是有意义吗?因此,身份验证应该适用于此..我尝试传递电子邮件参数,但现在毫无意义,我同意(缺乏想法)…但在此之前,如果您再次查看,我尝试使用用户名..不知道我还可以尝试什么..尝试将您的用户模型的用户名字段更改为电子邮件字段。只是暗中捅了一刀。用户名\字段从一开始就设置为电子邮件字段