首页 > 解决方案 > 如何在 django 中使用不同表的身份验证

问题描述

我创建了一个新模型并将数据存储在该表中。 如果我使用该authenticate方法,它会检查auth_user表以进行身份​​验证,而不是我的表。我正在使用PostgreSQL后端。 如何使用我创建的表进行身份验证。我是 Django 的初学者。

# models.py

from django.db import models


# Create your models here.
class register(models.Model):
    username=models.CharField(max_length=50)
    mob=models.BigIntegerField()
    password=models.CharField(max_length=50)

# views.py
def registeruser(request):
    if request.method == 'POST':
        username=request.POST['username']
        mob=request.POST['mob']
        password=request.POST['password1']
        password1=request.POST['password2']
        password=hashers.make_password(password)
        objects=register(username=username, password=password, mob=mob)
        objects.save()
        return render(request, "home.html")
    else:
        return render(request, "home.html")

def loginuser(request):
    usern=request.POST['username']
    passw=request.POST['password']
    user=auth.authenticate(request, username=usern, password=passw)
    if user is not None:
        auth.login(request, user)
        return redirect("/")
    else:
        return render(request, 'userpage.html', {'username': usern})

标签: djangodjango-models

解决方案


如果你想让 django 使用你的自定义用户模型,你需要AUTH_USER_MODEL在你的 settings.py 中指定:

# settings.py

AUTH_USER_MODEL = 'yourapp.YourModel'

您还必须USERNAME_FIELD在您的用户模型和set_password方法上指定默认authenticate功能才有用。

通常,最佳实践不是完全覆盖默认模型,而是AbstractBaseUser使用您的字段扩展抽象模型。

在 django 文档中阅读有关自定义身份验证的更多信息:https ://docs.djangoproject.com/en/2.2/topics/auth/customizing/


推荐阅读