Django自定义用户和AuthenticationForm

时间:2018-04-20 23:44:52

标签: python django django-authentication

我找到了其他人'解决方案很有帮助,但我仍然遇到问题。

使用自定义用户模型并使用AuthenticationForm表示支持自定义用户模型,我不断收到此错误:Please enter a correct username and password. Note that both fields may be case-sensitive.

我也无法使用authentication函数,因为它始终返回None

我的settings.py库存是我的应用名称。

AUTH_USER_MODEL = 'inventory.User'

以下是views.py

中的登录部分
def login_view(request):
    context = {}
    if request.method == 'POST':
        # print(request.POST)
        form = AuthenticationForm(data=request.POST)
        print(form)
        if form.is_valid():
            print('yay')

    elif request.method == 'GET':
        context['form'] = AuthenticationForm()

    return render(request, 'inventory/login.html', context)

这是我的models.py

class UserManager(AbstractUserManager):
    def create_user(self, username, first_name, last_name, perm, password):
        if not username:
            raise ValueError('Users must have a username')
        if not first_name:
            raise ValueError('Users must have a first name')
        if not last_name:
            raise ValueError('Users must have a last name')
        if not perm:
            raise ValueError('Users must have a position')

        user = self.model(
            username=username,
            first_name=first_name,
            last_name=last_name,
        )

        if perm == 'e':
            user.employee = True
        elif perm == 'm':
            user.manager = True
        elif perm == 'o':
            user.owner = True

        user.set_password(password)
        user.save(using=self._db)
        return user



class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(verbose_name='username', max_length=50, unique=True,)
    first_name = models.CharField(verbose_name='first name', max_length=50,)
    last_name = models.CharField(verbose_name='last name', max_length=50,)
    active = models.BooleanField(default=False)

    employee = models.BooleanField(default=False)
    manager = models.BooleanField(default=False)
    owner = models.BooleanField(default=False)

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['first_name', 'last_name']

    def __str__(self):
        return self.first_name + ' ' + self.last_name

    @property
    def is_employee(self):
        return self.employee

    @property
    def is_manager(self):
        return self.manager

    @property
    def is_owner(self):
        return self.owner

    @property
    def is_active(self):
        return self.active

    objects = UserManager()

以下是login.html

<form method="POST" action="{% url 'login' %}">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="login" />
</form>

我已经搜索了几个小时试图弄清楚我的问题是什么,查看AuthenticationForm文档/代码,看看它是否以某种方式搜索auth.User对象而不是我的inventory.User对象,它没有&# 39; t似乎是,特别是在文档声明它可以与自定义用户模型一起使用,只要您在AUTH_USER_MODEL中定义settings.py。提前谢谢。

1 个答案:

答案 0 :(得分:0)

你在问题​​的最上面说过:

  

我也无法使用authentication函数,因为它始终返回None

您的意思是djangos authenticate function吗?如果该函数返回None,则您的AuthenticationForm将继续无法登录。

尝试与此代码类似的内容:

from django.contrib.auth import authenticate
print(request.POST)
user = authenticate(**request.POST)  # pass all the keys to the function
if user is not None:
    print('A backend authenticated the credentials.')
    # Now you can try your Form again.
else:
    print('ERROR: no backend authenticated the credentials.')
    # Your Form will never login the user.

如果这不起作用,您的AuthenticationForm也可能无效。