4

我正在使用 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 }}and{{ form.password }}将分别自动生成 an<input id="id_username" maxlength="254" name="username" type="text">和 an <input id="id_password" name="password" type="password">。但我想为这些input字段添加一些额外的属性,例如placeholderclass。我在哪里可以定制这些?

4

2 回答 2

9

手动:

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

或通过小部件 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'}))
于 2013-05-29T20:29:47.787 回答
6

您可以使用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 %}

希望这可以帮助!

于 2013-05-29T20:29:08.443 回答