gpt4 book ai didi

python - 创建新表(模型)并将其与 Django 中的 auth_user 相关联

转载 作者:行者123 更新时间:2023-11-29 19:11:50 24 4
gpt4 key购买 nike

我正在尝试创建一个新模型来跟踪当前密码和最近使用的密码。我希望它看起来像这个粗略的例子:

ID --- CUR_PASS --- PREV_PASS
1 --- 123 --- 321
2 --- 456 --- 654

是否可以将ID设为我的auth_user表中的用户名

这是我到目前为止的类(class):

# class model to store previously used passwords
class oldPass(models.Model):
# username = models.ForeignKey('something') --> instead of ID?
current_pass = models.CharField(max_length=100)
prev_pass = models.CharField(max_length=100)

class Meta: # meta class to define the table name
db_table = "old_pass"

我正在尝试将 ID 作为用户名,并在 auth_user 中更改密码时,返回到 old_pass 表并比较值确保两者都不是。如果是其中任何一个,则返回一个错误。

我最大的问题是:

  1. 我不知道如何导入 auth_user,以便我可以将用户名分配给这个新表
  2. 我不知道如何将 ID 更改为用户名而不是数字。 (这可以使用ForeignKey 来完成吗?)
  3. 我希望能够将这些值与传入的变量进行比较...

#3 的示例: - 我想执行 User.set_password('pass') (以便对 pass 进行哈希处理),然后我想在提交 User.save() 之前将此新密码与 'current_pass' 和 'prev_pass' 进行比较。如果密码与使用的密码之一匹配,我想中止。

我正在使用 Django 1.9 和 Python 2.7.13

更新因此,查看收到的答案并研究更多信息...这是我的新类(class)

from django.contrib.auth.models import User
# class model to store previously used passwords
class oldPass(models.Model):
# username = models.ForeignKey(User) --> instead of ID?
current_pass = models.CharField(max_length=100)
prev_pass = models.CharField(max_length=100)

class Meta: # meta class to define the table name
db_table = "old_pass"

最佳答案

  1. from django.conf import settingssettings.AUTH_USER_MODEL 是您的 auth_user 模型。

  2. 使用如下所示的自定义 ID:id = models.CharField(primary_key=True)。但大多数情况下,ID 应该是一个毫无意义的字段。

  3. 您可以在执行User.set_password('pass')之前检查密码。

模型.py

class oldPass(models.Model):
user = models.ForeignKey(`settings.AUTH_USER_MODEL`)
current_pass = models.CharField(max_length=100)
prev_pass = models.CharField(max_length=100)

class Meta:
db_table = "old_pass"

View .py

if oldPass.objects.filter(user=user, pre_pass='pass').exists():
raise Error
user.set_password('pass')
user.save() #at the same time, update user's password in oldPass

关于python - 创建新表(模型)并将其与 Django 中的 auth_user 相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43022399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com