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.
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'}.
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.
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With