如何自定义django.forms生成的输入元素?

时间:2013-05-29 19:47:52

标签: django django-forms

我正在使用django.forms生成我的登录/注册页面,部分代码如下:

<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<table>
<tr>
    {# username is directed to email field in our model #}
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
{% if next %}
    <input type="hidden" name="next" value="{{ next }}" />
{% else %}
    <input type="hidden" name="next" value="{% url 'home' %}" />
{% endif %}
</form>

如您所见,{{ form.username }}{{ form.password }}将分别自动生成<input id="id_username" maxlength="254" name="username" type="text"><input id="id_password" name="password" type="password">。但我想为这些input字段添加一些额外的属性,例如placeholderclass。我在哪里可以自定义这些?

2 个答案:

答案 0 :(得分:7)

手动:

<input type="text" name="{{ form.field.html_name }}" placeholder="foo" value="{{ form.field.value }}" />

或通过widget attrs参数 https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs

class MyForm(forms.Form):
    field = forms.CharField(widget=forms.TextInput(attrs={'placehoder': 'foo', 'title': 'baz'}))

答案 1 :(得分:5)

您可以使用django-widget-tweaks这是一个非常好的库来调整django的小部件。我用过它很简单。

从他们的网站:

{% load widget_tweaks %}
<!-- change input type (e.g. to HTML5) -->

{% render_field form.search_query type="search" %}

<!-- add/change several attributes -->
{% render_field form.text rows="20" cols="20" title="Hello, world!" %}

<!-- append to an attribute -->
{% render_field form.title class+="css_class_1 css_class_2" %}

<!-- template variables can be used as attribute values -->
{% render_field form.text placeholder=form.text.label %}

希望这有帮助!