TIMEX
TIMEX

Reputation: 272274

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

Upvotes: 7

Views: 3166

Answers (3)

Wassim Katbey
Wassim Katbey

Reputation: 327

In the class wherein you specify your forms, you can set the 'widgets' per each form element. The 'widget' contains information on that element's attributes, etc.

Here's an example (applies if you're creating your form through ModelForm):

class BlogEntryForm(ModelForm):
    class Meta:
        model = BlogEntry
        fields = (
            'title',
            'category',
            'text_entry',
            'private'
        )

        widgets = {
            'category': forms.Select(
                attrs={
                    'class': 'form-control'
                },
                choices=[]
            ),
            'title': forms.TextInput(
                attrs={
                    'class': 'form-control',
                }
            ),
            'text_entry': forms.Textarea(
                attrs={
                    'id': 'text-editor',
                    'class': 'form-control',
                    'rows': '17',
                }
            ),
            'private': forms.CheckboxInput(
                attrs = {
                    'id': 'make-post-private',
                    'class': 'custom-control-input'
                }
            )
        }

Upvotes: 0

Mikhail Korobov
Mikhail Korobov

Reputation: 22248

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

{% load widget_tweaks %}
... 
{{ theform.address|attr:"placeholder:username" }}

Upvotes: 5

girasquid
girasquid

Reputation: 15506

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.

Upvotes: 9

Related Questions