Edgar Navasardyan
Edgar Navasardyan

Reputation: 4501

Setting HTML required attribute in Django formsets

To achieve client-side validation making the user to fill out non-null fields before submitting, I use the following code:

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)   
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            if field.required == True: 
                field.widget.attrs['required'] = ''

This translates to the following html in the template:

<input class="form-control" ........ required="">

Now, when I use formsets, the required HTML attribute does not appear in the tempalte. The question is, how do I make Django formsets inherit this required attribute from the original forms - if it's possible whatsoever?

MyFormSet =  modelformset_factory(MyModel, fields=(...))
formset = MyFormSet(queryset = MyModel.objects.filter(...))

Upvotes: 0

Views: 516

Answers (2)

Edgar Navasardyan
Edgar Navasardyan

Reputation: 4501

After spending three hours, I've solved the issue by setting a custom form in modelformset_factory. Maybe it will be useful for someone else

MyFormSet =  modelformset_factory(MyModel, MyForm)
formset = MyFormSet(queryset = MyModel.objects.filter(...))

Specifying MyForm effectively tells Django to inherit all widget attributes that you have once declared in the MyForm definition.

Using formset_factory is for some reasons a headache for me, primarily because it accepts values instead of querysets which means I have to bother about foreign key relationships.

Upvotes: 0

Lucas03
Lucas03

Reputation: 2347

How about creating formset from MyForm?

MyFormSet = forms.formset_factory(MyForm)

Upvotes: 1

Related Questions