动态为表单字段添加占位符
我有一个Django表单,里面有几个常见的字段:
first_name = forms.CharField(label=_("First Name"))
last_name = forms.CharField(label=_("Last Name"))
phone = USPhoneNumberField(label=_("Phone Number"))
email = forms.EmailField()
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))
在网站上显示这个表单时,我是用下面的代码来创建这些字段的:
<label for="id_first_name">First Name: </label>{{ form.first_name }}
<label for="id_last_name">Last Name: </label>{{ form.last_name }}
<p><label for="id_email">Email: </label>{{ form.email }}
<p><label for="id_phone">Phone: </label>{{ form.phone }}
<p><label for="id_password1">Password: </label>{{ form.password1 }}
<p><label for="id_password2">Password Confirmation: </label>{{ form.password2 }}
<p><input type="submit" value="Sign up" /></p>
问题是,我想给某些字段(比如邮箱、名字和姓氏)设置占位符,但我不想用那种普通的占位符,比如“邮箱地址”、“名字”等等。根据这个应用的业务逻辑,我希望这些占位符能显示实际的名字和邮箱地址,这些信息来自视图的上下文,但用户在最终提交之前仍然可以修改这些内容。
我想利用表单的便利性,但看起来没有简单的方法可以动态生成占位符属性,而不完全放弃Django表单,直接使用普通的HTML标签。有没有什么想法?
2 个回答
1
你可以在表单初始化的时候,动态地添加任何表单字段的属性,方法如下:
class MyForm(forms.Form):
field = forms.TextField()
def __init__(self, *args, **kwargs):
form = super(MyForm, self).__init__(*args, **kwargs)
form.fields['field'].widget.attrs['placeholder']='custom_placeholder'
不过,根据你的描述,你确定你需要占位符吗?还是说你希望表单字段里预先填入一个特定的值,这个值会在用户没有更改的情况下提交到服务器呢?
8
你可以动态地为表单字段设置占位符:
def someview(request):
form = SomeForm(..)
if some_condition:
form.fields['email'].widget.attrs['placeholder'] = instance.email