【问题标题】:Django - UserModel - How to create Custom Text Field within the django/contrib/auth/forms.pyDjango - UserModel - 如何在 django/contrib/auth/forms.py 中创建自定义文本字段
【发布时间】:2020-03-03 06:34:33
【问题描述】:

我的问题 - 如何在 django/contrib/auth/forms.py 中创建自定义文本字段。 ?

我正在尝试调整 Django 默认用户模型。我正在添加一个名为“bio”的测试字段

到目前为止,我在 /python3.6/site-packages/django/contrib/auth/forms.py 文件中的代码如下 -

class UserCreationForm(forms.ModelForm):
    """
    A form that creates a user, with no privileges, from the given username and
    password.
    """
    error_messages = {
        'password_mismatch': _("The two password fields didn't match."),
    }
    password1 = forms.CharField(
        label=_("Password"),
        strip=False,
        widget=forms.PasswordInput,
        help_text=password_validation.password_validators_help_text_html(),
    )
    password2 = forms.CharField(
        label=_("Password confirmation"),
        widget=forms.PasswordInput,
        strip=False,
        help_text=_("Enter the same password as before, for verification."),
    )

    bio = forms.CharField(   #FOO_bio  # this value --not getting saved in PSQL 
        label=_("bio_test within Forms.py"),
        #widget=forms.PasswordInput, #Didnt work thus switched to forms.TextInput
        widget=forms.TextInput, 
        strip=False,
        help_text=_("Enter some dummy BIO here ."),
    )

在此文件中定义的方法中 - def clean_password2(self) 的进一步下方,我正在尝试将“bio”添加为

def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        bio = self.cleaned_data.get("bio") # I have no clue how to do this ? 
        print(bio) #prints None in the terminal 
    

我知道 DICT -cleaned_data 中没有名为“bio”的键。

在文件 - /site-packages/django/contrib/auth/models.py 中,将“简历”添加为 models.TextField ,在类 class AbstractUser(AbstractBaseUser, PermissionsMixin):

bio = models.TextField(
        _('bio'), 
        max_length=500, blank=True)

自定义字段“bio”显示在注册表单中,测试用户输入一个文本值 - 表单被提交,但 psql 中没有保存“bio”的任何内容。新用户已注册,可以在终端的 psql 和 Django Admin 中看到。

也在 Django 管理员中 - 当我转到 URL - http://digitalcognition.co.in/admin/auth/user/16/change/ 时,我可以在“个人信息”部分中看到一个名为“Bio”的文本字段,但这又是空白的。 “电子邮件地址”、“用户名”和“密码”与往常一样。

【问题讨论】:

    标签: django


    【解决方案1】:

    不要修改默认的用户模型。正如the documentation中提到的:

    如果您希望存储与用户相关的信息,您可以使用 OneToOneField 到包含附加字段的模型 信息。这种一对一的模型通常称为轮廓模型,因为 它可能存储有关站点用户的非身份验证相关信息。

    而且你绝对不应该修改 django 代码。只需创建一个继承自 django 的 UserCreationForm 的新表单,然后在其中添加您的字段。

    查看接受的答案here

    【讨论】:

    • 感谢您的回答 - 我已经知道这些建议不要调整默认用户模型,我是从学习的角度这样做的。除非无法以这种方式添加新的自定义字段,否则我想添加这些并了解如何完成 - 再次感谢。
    • 我正在尝试链接答案中使用的方法,我需要发回我的结果,我赞成你的答案 - 谢谢
    • 关键是覆盖表单的 save() 方法,并确保将数据保存到那里的数据库中。祝你好运!
    猜你喜欢
    • 2022-06-13
    • 2021-02-09
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 2019-07-29
    • 2015-04-16
    • 2013-06-03
    • 2011-09-20
    相关资源
    最近更新 更多