gpt4 book ai didi

django - 如何添加占位符 UserCreationForm django?

转载 作者:行者123 更新时间:2023-12-02 00:27:13 24 4
gpt4 key购买 nike

我正在尝试将占位符添加到 UserCreationForm 中的用户名字段但我不明白该怎么做。我已经以这种方式更改了 forms.py 文件/lib/site-packages/django/contrib/auth/forms.py。

我将占位符添加到 password1 和 password2 字段并像这样工作:

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(attrs={'placeholder':'Password'}),
help_text=password_validation.password_validators_help_text_html(),
)
password2 = forms.CharField(
label=_("Password confirmation"),
widget=forms.PasswordInput(attrs={'placeholder':'Confirmar Password'}),
strip=False,
help_text=_("Enter the same password as before, for verification."),
)

我可以看到用户名字段可能来自类元:

class Meta:
model = User
fields = ("username",)
field_classes = {'username': UsernameField}

来自这门课,但我不确定

class UsernameField(forms.CharField):
def to_python(self, value):
return unicodedata.normalize('NFKC', super().to_python(value))

我不明白如何在用户名字段中添加占位符

这是我的html

<form method="post" action=".">
{% csrf_token %}
{% for field in form %}
{{ field }}<br />
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
{% endfor %}
<input id="submit-signup-btn" type="submit" value="Iniciar"/>
</form>

最佳答案

看了一会儿之后,我找到了一种方法,我就是这样做的:

在文件/lib/site-packages/django/contrib/auth/forms.py 中,在 UserCreationForm 类中,Meta 类下有一个 init 函数,您可以在其中看到这一行

self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': 
True})

我将占位符添加到更新方法的行尾,如下所示:

self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True,
'placeholder':'Nome Perfil'})

关于django - 如何添加占位符 UserCreationForm django?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53243932/

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