如何在Django表单的输入中添加额外的属性?

TIM*_*MEX 6 html javascript css python django

{{ theform.address }}

{{ theform.phone }}
Run Code Online (Sandbox Code Playgroud)

这就是我在模板中所做的.

但是,如果我想添加placeholder="Username"到输入文本字段该怎么办?(自定义属性)

<input type="text" name="address" id="id_address" placeholder="username"/>
Run Code Online (Sandbox Code Playgroud)

gir*_*uid 7

attrs关键字参数添加到字段构造函数中widget,并在其中包含写入属性:

address = forms.TextField(widget=forms.TextInput(attrs={'placeholder': 'username'}))
Run Code Online (Sandbox Code Playgroud)

如果你想看到它的实际效果,请看看django-registration的forms.py.


Mik*_*bov 5

或者,您可以使用http://pypi.python.org/pypi/django-widget-tweaks应用程序:

{% load widget_tweaks %}
... 
{{ theform.address|attr:"placeholder:username" }}
Run Code Online (Sandbox Code Playgroud)