0

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(...))

2 Answers 2

1

How about creating formset from MyForm?

MyFormSet = forms.formset_factory(MyForm)
Sign up to request clarification or add additional context in comments.

2 Comments

formset_factory does not seem to allow for filtering queryset
But it's correct that formset_factory really solved the problem of required.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.