# Why is my formset not initialised correctly? formset.is\_valid() fails!

**URL:** <https://forum.djangoproject.com/t/why-is-my-formset-not-initialised-correctly-formset-is-valid-fails/22831>\
**Category:** Forms & APIs\
**Created:** [August 6, 2023, 1:41pm UTC](https://forum.djangoproject.com/t/why-is-my-formset-not-initialised-correctly-formset-is-valid-fails/22831 "2023-08-06T13:41:44Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![petasis](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/petasis/32/6393_2.png) [@petasis](https://forum.djangoproject.com/u/petasis)\
**Post date:** [August 6, 2023, 1:41pm UTC](https://forum.djangoproject.com/t/why-is-my-formset-not-initialised-correctly-formset-is-valid-fails/22831/1 "2023-08-06T13:41:45Z")

</div>

Hi all,

I have created a formset:

```auto
ActivityStepFormSet = inlineformset_factory(
    Activity,
    ActivityStep,
    form=ActivityStepForm, # this is ModelForm
    extra=0, # number of extra empty forms to display
    min_num=1, # number of minimum filled forms
    can_delete=False, # show a checkbox in each form to delete the row
)

```

The form is shown, I added a new row (form in the formset through javascript), updated TOTAL-FORMS to 2. When the form is posted, I receive the POST data, and I provide the following kwargs to initialise an ActivityStepFormSet ():

```auto
formset_kwargs: {'data': <QueryDict: {'csrfmiddlewaretoken': ['zFzWtsyT5IynU4auVsLE1jhuvc2BrvoFknLEQSHpzactEZ28rfGQcCkWPi0sZ1Cq'], 'activity_digitisation_wizard_view-current_step': ['add_activity'], 'add_activity-name': ['Sample Activity 1'], 'add_activity-description': [''], 'add_activity-name_local': [''], 'add_activity-description_local': [''], 'add_activity-language_local': [''], 'add_activity-created_by': ['2'], 'add_activity-TOTAL_FORMS': ['2'], 'add_activity-INITIAL_FORMS': ['0'], 'add_activity-MIN_NUM_FORMS': ['1'], 'add_activity-MAX_NUM_FORMS': ['1000'], 'add_activity- __prefix__ -created_by': [''], 'add_activity-0-created_by': ['2'], 'add_activity-1-created_by': [''], 'add_activity- __prefix__ -name': [''], 'add_activity- __prefix__ -description': [''], 'add_activity- __prefix__ -name_local': [''], 'add_activity- __prefix__ -description_local': [''], 'add_activity- __prefix__ -language_local': [''], 'add_activity- __prefix__ -activity': [''], 'add_activity- __prefix__ -stimulus': [''], 'add_activity- __prefix__ -id': [''], 'add_activity-0-name': ['help'], 'add_activity-0-description': [''], 'add_activity-0-name_local': [''], 'add_activity-0-description_local': [''], 'add_activity-0-language_local': [''], 'add_activity-0-activity': [''], 'add_activity-0-stimulus': ['1'], 'add_activity-0-id': [''], 'add_activity-1-name': ['help2'], 'add_activity-1-description': [''], 'add_activity-1-name_local': [''], 'add_activity-1-description_local': [''], 'add_activity-1-language_local': [''], 'add_activity-1-activity': [''], 'add_activity-1-stimulus': ['1'], 'add_activity-1-id': [''], '_next': ['Next']}>, 'files': <MultiValueDict: {}>, 'prefix': 'add_activity', 'initial': [{'created_by': <SimpleLazyObject: <User: petasis>>}, {'created_by': <SimpleLazyObject: <User: petasis>>}]}

```

However, calling is\_valid() on the form object, returns false:

```auto
False [{}, {'created_by': ['This field is required.']}]

```

I cannot understand why the second form is invalid, since I have provided a list of two “created\_by” in the argument ‘initial’.

What can be wrong?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 6, 2023, 1:59pm UTC](https://forum.djangoproject.com/t/why-is-my-formset-not-initialised-correctly-formset-is-valid-fails/22831/2 "2023-08-06T13:59:21Z")

</div>

Please post your ActivityStep model and your ActivityStepForm form, along with the view.

---

<div class="post-metadata">

**Author:** ![petasis](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/petasis/32/6393_2.png) [@petasis](https://forum.djangoproject.com/u/petasis)\
**Post date:** [August 6, 2023, 2:12pm UTC](https://forum.djangoproject.com/t/why-is-my-formset-not-initialised-correctly-formset-is-valid-fails/22831/3 "2023-08-06T14:12:46Z")

</div>

```auto
class VASTForm(ModelForm):
    class Meta:
        exclude = ('uuid', 'created', 'updated', 'name_md5', 'id')
        widgets = {
            "date": AdminSplitDateTime(),
            "date_from": AdminSplitDateTime(),
            "date_to": AdminSplitDateTime(),
            "created_by": forms.HiddenInput(),
        }

class ActivityStepForm(VASTForm):
    class Meta(VASTForm.Meta):
        model = ActivityStep

class VASTObject(Model):
    uuid = models.UUIDField(default = uuid.uuid4, editable = False)
    name = models.CharField(max_length=255, default=None)
    name_md5 = models.CharField(max_length=64, default=None, null=True, blank=True, editable=False)
    description = models.CharField(max_length=255, default=None, null=True, blank=True)
    name_local = models.CharField(max_length=255, default=None, null=True, blank=True)
    description_local = models.CharField(max_length=255, default=None, null=True, blank=True)
    language_local = models.ForeignKey('Language', on_delete=models.CASCADE, default=None, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True, null=True)
    updated = models.DateTimeField(auto_now=True, null=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=False, blank=False, on_delete=models.CASCADE)
    class Meta(AutoUpdateTimeFields.Meta):
        abstract = True

class VASTObject_NameUserGroupUnique(VASTObject):
    class Meta(VASTObject.Meta):
        abstract = True
        # Enforce a policy for the name to be unique (for each user)
        unique_together = [["name", "created_by"]]

class ActivityStep(VASTObject_NameUserGroupUnique):
    activity = models.ForeignKey('Activity', on_delete=models.CASCADE, default=None, null=False, blank=False)
    stimulus = models.ForeignKey('Stimulus', on_delete=models.CASCADE, default=None, null=False, blank=False)

```

The view is a `NamedUrlSessionWizardView` from formtools package.

---

<div class="post-metadata">

**Author:** ![petasis](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/petasis/32/6393_2.png) [@petasis](https://forum.djangoproject.com/u/petasis)\
**Post date:** [August 6, 2023, 2:28pm UTC](https://forum.djangoproject.com/t/why-is-my-formset-not-initialised-correctly-formset-is-valid-fails/22831/4 "2023-08-06T14:28:12Z")

</div>

I have restarted django, and reseted session data. Starting with a single form in formset, and with everything unfilled, is\_valid() returns:

```auto
False [{'name': ['This field is required.'], 'stimulus': ['This field is required.'], 'id': ['This field is required.']}]

```

According to my `ActivityStepForm` (which inherits Meta from VASTForm), ‘id’ should not be there.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 6, 2023, 2:38pm UTC](https://forum.djangoproject.com/t/why-is-my-formset-not-initialised-correctly-formset-is-valid-fails/22831/5 "2023-08-06T14:38:49Z")

</div>

Unless your form is “insert only”, I don’t _think_ you can validly exclude the id field in a ModelForm. On any “edit” operation, Django needs the ID to identify which entity is being edited. (See [Creating forms from models | Django documentation | Django](https://docs.djangoproject.com/en/4.2/topics/forms/modelforms/#using-the-formset-in-the-template))

---

<div class="post-metadata">

**Author:** ![petasis](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/petasis/32/6393_2.png) [@petasis](https://forum.djangoproject.com/u/petasis)\
**Post date:** [August 6, 2023, 2:41pm UTC](https://forum.djangoproject.com/t/why-is-my-formset-not-initialised-correctly-formset-is-valid-fails/22831/6 "2023-08-06T14:41:27Z")

</div>

I think the problem originates from the way I add the new rows/forms.

In javascript, I copy the empty form, which has created\_by empty. So, this ends also empty in the data, and validation fails.

I removed id by explicitly set exclude=(‘id’,) in the call to `inlineformset_factory`. I shouldn’t need to do that, but…

Is there any way to set default values to the empty form?

---

<div class="post-metadata">

**Author:** ![petasis](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/petasis/32/6393_2.png) [@petasis](https://forum.djangoproject.com/u/petasis)\
**Post date:** [August 6, 2023, 2:42pm UTC](https://forum.djangoproject.com/t/why-is-my-formset-not-initialised-correctly-formset-is-valid-fails/22831/7 "2023-08-06T14:42:40Z")

</div>

Yes, my forms are “insert only”. How can I specify this?  
(Its a wizard designed to add new objects)

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 6, 2023, 2:48pm UTC](https://forum.djangoproject.com/t/why-is-my-formset-not-initialised-correctly-formset-is-valid-fails/22831/8 "2023-08-06T14:48:56Z")

</div>

Upon second thought - I still think you need the id field. It can remain hidden, but I believe it’s necessary. (My current guess would be that Django uses an empty ID field to identify that this is an insert vs an update.) You need an ID field, it would be None on a new row.

When you copy the empty forms, are you also changing the name fields to reflect their new instance number?

If you haven’t done so before, I suggest you take the simplest case for a formset and render it with two or three rows along with one or two extras, and visually examine what gets rendered to help visualize how a formset works. (I know that helped _me_ a great deal when I started working with them.) It’ll also help you know what to look for when checking your JavaScript for adding new rows.

---

<div class="post-metadata">

**Author:** ![petasis](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/petasis/32/6393_2.png) [@petasis](https://forum.djangoproject.com/u/petasis)\
**Post date:** [August 6, 2023, 3:32pm UTC](https://forum.djangoproject.com/t/why-is-my-formset-not-initialised-correctly-formset-is-valid-fails/22831/9 "2023-08-06T15:32:58Z")

</div>

Yes, I change the ids (I have posted an output in the first post). Now I am trying to change the data passed when initialising the formset…

---

<div class="post-metadata">

**Author:** ![petasis](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/petasis/32/6393_2.png) [@petasis](https://forum.djangoproject.com/u/petasis)\
**Post date:** [August 6, 2023, 3:49pm UTC](https://forum.djangoproject.com/t/why-is-my-formset-not-initialised-correctly-formset-is-valid-fails/22831/10 "2023-08-06T15:49:32Z")

</div>

This seems to work:

```auto
class ActivityForm(VASTForm):
    activity_steps = ActivityStepFormSet()
    def __init__ (self, *args, **kwargs):
        formset_kwargs = copy.deepcopy(kwargs)
        # Get prefix
        prefix = kwargs.get('prefix')
        # Get number of forms
        data = kwargs.get('data')
        if data:
            total_forms = int(data.get(f'{prefix}-TOTAL_FORMS')[0])
            # Set created_by...
            for key in kwargs.get('initial').keys():
                value = formset_kwargs['data'][f'{prefix}-0-{key}']
                for i in range(1, total_forms):
                    formset_kwargs['data'][f'{prefix}-{i}-{key}'] = value
        else:
            total_forms = 1
        # Give as many initial objects as forms...
        formset_kwargs['initial'] = [kwargs.get('initial')] * (total_forms)
        # TODO: Handle instances
        formset_kwargs.pop('instance')
        self.activity_steps = ActivityStepFormSet(*args, **formset_kwargs)
        super(). __init__ (*args, **kwargs)

    class Meta(VASTForm.Meta):
        model = Activity

```

(My formset is shown as a “field” in the parent model)
