21👍
As of Django 1.6, you can use the widgets
parameter of modelformset_factory
in order to customize the widget of a particular field:
AuthorFormSet = modelformset_factory(Author, widgets={
'name': Textarea(attrs={'cols': 80, 'rows': 20})
})
and therefore the same parameter for inlineformset_factory
(which uses modelformset_factory
):
AuthorInlineFormSet = inlineformset_factory(Author, Book, fields=['name'], widgets={
'name': Textarea(attrs={'cols': 80, 'rows': 20})
})
6👍
This is an example of customizing one field using formfield_callback:
def formfield_callback(field):
if isinstance(field, models.ChoiceField) and field.name == 'target_field_name':
return fields.ChoiceField(choices = SAMPLE_CHOICES_LIST, label='Sample Label')
return field.formfield()
FormSet = inlineformset_factory(ModelA, ModelB, extra=1, formfield_callback = formfield_callback)
- How to make Django Password Reset Email Beautiful HTML?
- Geodjango using mysql
- AWS Elastic Beanstalk Container Commands Failing
- Django – Check diference between old and new value when overriding save method
- Django multi-table inheritance, how to know which is the child class of a model?
3👍
You need to define a form and update widget in the Meta
class. Look at Overriding the default field types or widgets
2👍
you can subclass the formset and override the add_fields method. This worked for me and I am using Django 1.5 🙁 .
AuthorInlineFormSet = inlineformset_factory(Author, Book)
class AuthorFormSet(AuthorInlineFormSet):
def add_fields(self, form, index):
super(ReferenceForm,self).add_fields(form,index)
form.fields["name"] = forms.CharField(widget=forms.TextInput())
- Django- getting a list of foreign key objects
- How to create or register User using django-tastypie API programmatically?
- Django : Can we use .exclude() on .get() in django querysets
0👍
I know this is a really old thread. Now we can do this using django ModelForm itself.
Add your model form in forms.py
with widgets.
forms.py
class QAForm(forms.ModelForm):
class Meta:
model = QA
fields = ['question', 'answer', 'status']
widgets = {
'question': widgets.Textarea(
attrs={
'class': 'form-control',
'rows': 3,
'cols': 40
}
),
'answer': widgets.Textarea(
attrs={
'class': 'form-control',
'rows': 3,
'cols': 40
}
),
'status': widgets.Select(
attrs={
'class': 'form-select'
}
)
}
pass it using from
parameter for your modelformset_factory
like following in your views.py
views.py
QAFormSet = modelformset_factory(
models.QA,
fields=["question", "answer", "status"],
form=QAForm
)
- How to add anchor to django url in template
- Django – authentication, registration with email confirmation
- Installed Virtualenv and activating virtualenv doesn't work
- Reset SQLite database in Django
- How do you create a Django HttpRequest object with the META fields populated?