我已经在该表中创建了一个新模型并存储了数据。如果我使用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})
如果您希望django使用自定义用户模型,则需要在设置中指定 AUTH_USER_MODEL
.py:
# settings.py
AUTH_USER_MODEL = 'yourapp.YourModel'
您还必须在用户模型上指定 USERNAME_FIELD
和默认authenticate
函数的set_password
方法。
通常,最好的做法不是要完全覆盖默认模型,而是用您的字段扩展AbstractBaseUser
抽象模型。
在Django文档中阅读有关自定义身份验证的更多信息:https://docs.djangoproject.com/en/2.2/topics/auth/customizing/