django - 如何在 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})
解决方案
如果你想让 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/
推荐阅读
- ios - UIImagePickerController isSourceTypeAvailable(type) 始终为真
- javascript - 如何使用 dataTable 过滤日期列
- apache-kafka - 多个分区上的 Spring Kafka 和轮询策略
- java - 如何修复 Object 无法转换为 javafx.scene.Node
- graalvm - Micronaut 数据、GraalVM、AWS 构建失败
- c - M_CACHE、M_DEVBUF、M_TEMP的区别
- python - 通过频繁向 DHT 发布消息来快速获得同行?
- spring - 如何在 Spring Security OAuth Provider 中实现 PKCE 授权码?
- postgresql - 捕获到 Postgres 数据库的每个非 ssl 连接
- javascript - 如何在 Js 中为所有树数组的对象添加一个项目?