Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an attribute to the <input> tag for a django ModelForm field

Tags:

I have a django model that I'm displaying as a form using a ModelForm. The defaults work very well for me for the most part.

However, I would like my html <input ...> tags to have one additional attribute, namely I would like to include a placeholder attribute, like the following:

<input placeholder="{{field.label}}" ... /> 

What is the easiest way to add this attribute to my html? As far as I can tell it appears I need to implement my own filter to output the field, but this seems like overkill when all i want to do is leave everything alone but add one additional attribute.

like image 277
emmby Avatar asked Dec 03 '10 01:12

emmby


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'}.

What is ModelForm in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.


2 Answers

See the documentation

class AuthorForm(ModelForm):     class Meta:         model = Author         widgets = {             'name': TextInput(attrs={'placeholder': 'name'}),         } 

You could always create your own widget that derives from TextInput and includes the placeholder attribute, and use the widgets dictionary to simply map fields to your new widget without specifying the placeholder attribute for every field.

like image 58
Josh Smeaton Avatar answered Oct 07 '22 10:10

Josh Smeaton


Personally I prefer to use this method:

def __init__(self, *args, **kwargs):     super(MyForm, self).__init__(*args, **kwargs)     self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or '[email protected]' 

It required more code if you don't have __init__ yet, but you don't need to specify the widget.

like image 29
Mark Avatar answered Oct 07 '22 11:10

Mark