57
You can do the following:
#forms.py
class ProductForm(ModelForm):
class Meta:
model = Product
exclude = ('updated', 'created')
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['description'].widget = TextInput(attrs={
'id': 'myCustomId',
'class': 'myCustomClass',
'name': 'myCustomName',
'placeholder': 'myCustomPlaceholder'})
33
Field ids should be generated automatically by django, to override other fields:
class ProductForm(ModelForm):
class Meta:
model = Product
exclude = ('updated', 'created')
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs\
.update({
'placeholder': 'Name',
'class': 'input-calss_name'
})
- [Django]-How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi?
- [Django]-Custom django admin templates not working
- [Django]-Import error django corsheaders
27
I really like Dmitriy Sintsovโs answer but it doesnโt work. Hereโs a version that does work:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
'class': 'form-control'
})
update
add this condition for better
if self.fields[field].widget.__class__.__name__ in ('AdminTextInputWidget' , 'Textarea' , 'NumberInput' , 'AdminURLFieldWidget', 'Select'):
self.fields[field].widget.attrs.update({ 'class': 'form-control' })
- [Django]-How to remove all relations from manytomany?
- [Django]-FileUploadParser doesn't get the file name
- [Django]-Django tests โ patch object in all tests
20
You can update forms.py as below
class ProductForm(ModelForm):
class Meta:
model = Product
exclude = ('updated', 'created')
widgets={
"name":forms.TextInput(attrs={'placeholder':'Name','name':'Name','id':'common_id_for_imputfields','class':'input-class_name'}),
"description":forms.TextInput(attrs={'placeholder':'description','name':'description','id':'common_id_for_imputfields','class':'input-class_name'}),
}
- [Django]-How can I test https connections with Django as easily as I can non-https connections using 'runserver'?
- [Django]-From virtualenv, pip freeze > requirements.txt give TONES of garbage! How to trim it out?
- [Django]-Where should utility functions live in Django?
7
Slightly modified version of excellent mariodev answer, adding bootstrap class to all form fields, so I do not have to re-create form input widgets for each field manually (short Python 3.x super()):
class ProductForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({
'class': 'form-control'
})
- [Django]-How to move a model between two Django apps (Django 1.7)
- [Django]-Django comparing model instances for equality
- [Django]-Rendering JSON objects using a Django template after an Ajax call
3
Adding to answer from Derick Hayes I created a class BasicForm which extends forms.ModelForm that adds the bootstrap classes to every form that extends it.
For my forms I just extend BasicForm instead of model form and automatically get bootstrap classes on all forms. I went a step further and append the classes to any custom css classes which may already be there.
class BaseModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BaseModelForm, self).__init__(*args, **kwargs)
# add common css classes to all widgets
for field in iter(self.fields):
#get current classes from Meta
classes = self.fields[field].widget.attrs.get("class")
if classes is not None:
classes += " form-control"
else:
classes = "form-control"
self.fields[field].widget.attrs.update({
'class': classes
})
- [Django]-In Django is there a way to display choices as checkboxes?
- [Django]-Get user profile in django
- [Django]-Using Python's os.path, how do I go up one directory?
3
add_class filter for adding a CSS class to form field:
{% load widget_tweaks %}
<form enctype="multipart/form-data" action="{% url 'add_a_product' %}" method="post">
<div id="name">
{{form.name|add_class:"input-calss_name"}}
</div>
<div id="description">
{{form.description|add_class:"input-calss_name"}}
</div>
</form>
- [Django]-How to get Request.User in Django-Rest-Framework serializer?
- [Django]-Plug in django-allauth as endpoint in django-rest-framework
- [Django]-How to submit form without refreshing page using Django, Ajax, jQuery?
2
You can do the following:
class ProductForm(ModelForm):
name = forms.CharField(label='name ',
widget=forms.TextInput(attrs={'placeholder': 'name '}))
- [Django]-Django Model โ Get distinct value list
- [Django]-List field in model?
- [Django]-ManyRelatedManager object is not iterable
0
I know this is an old question but if someone is still looking to add custom class to all of his form fields, then you can use this one liner
class ProductForm(ModelForm):
class Meta:
model = Product
exclude = ('updated', 'created')
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
custom_attrs = {
'class': 'form-control',
'toggle-data': 'mydiv',
}
# adds our custom_attrs to each element of the form
[self.fields[i].widget.attrs.update(custom_attrs) for i in self.fields]
- [Django]-Get the list of checkbox post in django views
- [Django]-User Registration with error: no such table: auth_user
- [Django]-How to recursively query in django efficiently?