Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add an extra attribute in my input for Django forms?

{{ theform.address }}

{{ theform.phone }}

This is what I do in my templates.

However, what if I want to add placeholder="Username" to the input text field? (Custom attribute)

<input type="text" name="address" id="id_address" placeholder="username"/>
like image 995
TIMEX Avatar asked Jan 06 '11 22:01

TIMEX


People also ask

How do I add a class or id attribute to a Django form field?

In order to add a class or id attribute to a form in Django, we have to place a widget=form. TextInput (or widget= form. EmailInput, if email input) within the form field (because it's a text field). Inside of this widget, we then have to put, attrs={'class':'some_class'}.

How do I create a choice field in Django?

ChoiceField in Django Forms is a string field, for selecting a particular choice out of a list of available choices. It is used to implement State, Countries etc. like fields for which information is already defined and user has to choose one. It is used for taking text inputs from the user.

What is Attrs Django?

attrs . A dictionary containing HTML attributes to be set on the rendered DateInput and TimeInput widgets, respectively. If these attributes aren't set, Widget. attrs is used instead.


2 Answers

Add the attrs keyword argument to your field constructor's widget, and include write your attribute in there:

address = forms.TextField(widget=forms.TextInput(attrs={'placeholder': 'username'}))

If you want to see it in action, take a look at django-registration's forms.py.

like image 170
girasquid Avatar answered Nov 13 '22 14:11

girasquid


Alternatively, you can use the http://pypi.python.org/pypi/django-widget-tweaks app:

{% load widget_tweaks %}
... 
{{ theform.address|attr:"placeholder:username" }}
like image 28
Mikhail Korobov Avatar answered Nov 13 '22 14:11

Mikhail Korobov