如何在注册视图(forms.PasswordInput())Django中设置小部件的占位符



我正试图给我的{{form.password1}}}一个占位符。

#The concept is like this:
<input type="password" placeholder="password">

我试着用django在django做这件事,这是我的注册表格:

from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django import forms
class CreateUser(UserCreationForm):
class Meta:
model = User
fields = ['username','email','password1', 'password2']
widgets = {
'username' : forms.TextInput(attrs={'class':'username', 'placeholder':'Username'}),
'email' : forms.TextInput(attrs={'placeholder':'Email'}),
'password1' : forms.PasswordInput(attrs = {'placeholder': 'Password'}),
'password2' : forms.PasswordInput(attrs={'placeholder':'Confirm Your Password'}),
}

但它没有显示password1和password2占位符这是我的寄存器.html:

<form method="POST">
{% csrf_token %}
<div>{{form.username}}</div>
<div>{{form.email}}</div>
<div>{{form.password1}}</div>
<div>{{form.password2}}</div>
<input type="submit" placeholder="Register">
</form>

我实际上回答了我的问题,我想这是最好的答案,它是通过使用Django Tweaks您首先需要从终端安装Django Twiaks,使用:

pip3 install django-widget-tweaks #on linux and mac
pip install django-widget-tweaks # on windows

然后你需要将其添加到设置.py

INSTALLED_APPS = [
.....
'widget_tweaks',
.....
]

你需要在你的html文件中这样做:

{% load widget-tweaks %}
{% render_field your_form.your_field class="your class" placeholder="your placeholder" ... %}
# like that you can put any attr you want 

希望你喜欢它。希望它能帮助你。如果仍然没有得到,请检查https://www.youtube.com/watch?v=VYs-u0g_1A

最新更新