Django forms: Custom attributes for input tag

While making a form directly in html you may have done

<input id="keywords" type="text" name="keywords" placeholder="Enter your keywords here">

to make a input field that looks like :

enter_your_keywors_here

But in django Forms or ModelForms automatically generate some boilerplate code for you including that input tag.
You may be doing {{ form.as_p }} or {{ form.tag }} in the templates, there is no option(or not an obvious one) to do this directly into templates.
But you can do this in __init__ function of your Form or ModelForm like the following

class TagsForm(forms.ModelForm):
	class Meta:
		model = Tags
		fields = ("keywords",)

	def __init__(self, *args, **kwargs):
		super(SearchForm, self).__init__(*args, **kwargs)
		self.fields['keywords'].widget.attrs['placeholder'] = "Enter your keywords here"

Similarly you can add other attributes as well:

self.fields['keywords'].widget.attrs['value'] = "sensible default"

this will add value attribute in the input tag

<input id="keywords" type="text" name="keywords" value="sensible default">
Advertisements
Posted in Django, Prgramming/Coding, python, Technical

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: