I'd like to set the class attribute for the TextInput Widget to one value for all the fields in my form that use it without having to list them all in Meta: widgets = {.... Is this possible?
Thanks.
To create ModelForm in django, you need to specify fields. Just associate the fields to first_name and lastName. Under the Meta class you can add : fields = ['first_name','lastName']. @Shishir solution works after I add that line. or you can try solution in Jihoon answers by adding vacant fields.
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
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.
A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting <! DOCTYPE html> .
For ModelForm we can use this.
from django import forms
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
# change a widget attribute:
self.fields['user_permissions'].widget.attrs["size"] = 5
self.fields['user_permissions'].widget.attrs["class"] = 'form-control required'
class Meta:
model = User
You can override the constructor in order to modify all TextInput widgets:
from django import forms
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
if field.widget.__class__ == forms.widgets.TextInput:
if 'class' in field.widget.attrs:
field.widget.attrs['class'] += ' my-class'
else:
field.widget.attrs.update({'class':'my-class'})
class Meta:
model = MyModel
can you override init with a decorator? also, there should be an if statement before the attrs.update() becuase I want to set a default rather than override what may already be there. – Kevin
Untested, but I guess you can just inherit from MyForm if you use this a lot.
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