0

How do I change a field of a inline formset from not required to required in the view?

For example, for a form, it would be form.fields['field name'].required = True

How do I replicate this setting for an inline formset?

I tried formset.fields['field name'].required = True, but was given the error, 'formset' object has no attribute fields.

  • have you seen [this](https://stackoverflow.com/questions/2406537/django-formsets-make-first-required) – mh-firouzjah Mar 30 '21 at 20:13
  • for form in formset: – JustLearning123 Mar 31 '21 at 16:44
  • In my view, if I loop through each form in the formset, form.fields['field_name'].required = True sets it to true, but it still processes the form like it is valid. Same if I set it form.fields['field_name].empty_permitted = False. – JustLearning123 Mar 31 '21 at 16:50
  • Regarding your link provided, how do I go about setting up the __init__ and formset creation if I built my inline formset in forms.py? – JustLearning123 Mar 31 '21 at 19:28
  • you could define form to be used as formset. read the django docs about formset & mdelformset. – mh-firouzjah Apr 01 '21 at 09:14
  • I ended up making the fields required using widgets in forms.py. Now my issue is the save draft button will not save unless all fields are completed (because they are currently required). Is there a way to make the fields not required when the 'save draft' button is clicked? – JustLearning123 Apr 01 '21 at 16:27

1 Answers1

-1

Since inline formsets are actually a list of forms, you should loop over them to modify fields of each form. For example, in order to make all the fields of each form in the inline formset as not required, you could perform this in the view:

# modify all the fields
for form in inline_formset:
    for field in form.fields.values():
        field.required = False

# modify a particular field
for form in inline_formset:
    form.fields['field'].required = False

For the last part in the comments, fields are required in form because they are required in the model, so you could modify the model's field and use blank=True, null=True or set a default to it.

irvoma
  • 137
  • 3