Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize the input element generated by django.forms?

I'm using django.forms to generate my login/signup page, part of code is as follows:

<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>

As you can see, the {{ form.username }} and {{ form.password }} will automatically generate an <input id="id_username" maxlength="254" name="username" type="text"> and an <input id="id_password" name="password" type="password"> respectively. But I want to add some extra attributes to these input fields, like placeholderand class. Where can I customize these?

like image 663
chaonextdoor Avatar asked Dec 06 '22 07:12

chaonextdoor


1 Answers

Either manually:

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

Or via the widget attrs argument 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'}))
like image 147
Yuji 'Tomita' Tomita Avatar answered Mar 05 '23 18:03

Yuji 'Tomita' Tomita