[英]How to use two fields as username in Django custom user model?
我有員工表(舊版),其中包含字段 Employee_no、Company_name 和 Password。 我如何將當前表用作 Django 用戶 model? Employee_no 是重復的,但與 company_name 結合,它將是唯一的。
我需要使用 employee_no 和 company_name 作為用戶名來登錄。
員工號碼 | 公司名 | 密碼 |
---|---|---|
1個 | 蘋果 | 任何密碼 |
1個 | 三星 | 任何密碼 |
2個 | 蘋果 | 任何密碼 |
3個 | 三星 | 任何密碼 |
3個 | 谷歌 | 任何密碼 |
這是一個示例。它將用於案例或 email 或電話號碼
try:
user_obj = User.objects.get(Q(email=email_or_mobile) | Q(mobile_number=email_or_mobile))
except User.DoesNotExist:
raise Exception("Invalid email or mobile number")
if not user_obj.check_password(password):
raise Exception("Invalid password")
if user_obj.is_active:
login(request,user)
Django 強制您在用戶 model 中擁有唯一的USERNAME_FIELD
,以便使用它提供的所有開箱即用的功能。 但是如果你真的需要它,你總是可以自定義它(需要一些額外的工作)。
在您的情況下,您需要一個用戶 model,其中包含兩個唯一性定義的字段。 這意味着擁有一個自定義用戶 model並實現您的自定義身份驗證后端
對於用戶 model 你應該有這樣的東西:
class User(AbstractUser):
username = None
employee_no = models.IntergerField()
company_name = models.CharField(max_lenght=100)
USERNAME_FIELD = "employee_no" # Not really used, but required by Django
# Completes custom User subclassing ...
class Meta:
# This is required for your design in order to have database integrity
unique_together = ('employe_no', 'company_name')
如果您嘗試使用此用戶 model 運行服務器,您將收到系統檢查錯誤
你應該添加到你的設置
SILENCED_SYSTEM_CHECKS = ["auth.E003", "auth.W004"]
現在您必須實現自定義身份驗證后端,以便根據兩個字段對用戶進行身份驗證。 對於那個只是子類django.contrib.auth.backends.BaseBackend
並實現您的身份驗證邏輯。
像這樣:
class CustomBackend(BaseBackend):
def authenticate(self, request, employee_no=None, company_name=None, password=None, **kwargs):
if employee_no is None or company_name is None or password is None:
return
try:
user = UserModel._default_manager.get(employee_no=employee_no, company_name=company_name)
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
並將此后端添加到AUTHENTICATION_BACKENDS
列表中的設置(虛線字符串路徑)
最后,您必須確保在登錄視圖中傳遞正確的參數以驗證方法,並非常小心其他需要標准 Django 用戶 model 的集成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.