2

I'm either missing something very simple (and my Google-Fu is lacking), or I'm way off track. You make the call!

I'd like to write a test to exercise POSTing a formset to a view.

# get the modelformset from the view
response = self.client.get("/myview")
formset = response.context['formset']

# change the values in the underlying form
for form in enumerate(formset):
    form.instance['something'] = i

# how do I post the formset back to myview?  this does NOT work...
response = self.client.post("/myview", formset, follow=True)


AttributeError: 'MyFormSet' object has no attribute 'items'

The error makes complete sense, because I need to pass a dictionary as the second argument, not a Formset. I'm hoping that there's some method on Formset that will give me the appropriate dictionary (with the management form info), but I can't find it for the life of me.

UPDATE:

I got it working by doing this:

    data = {}
    for field in formset.management_form:
        data["-".join((formset.management_form.prefix, field.name))] = field.value()
    for form in formset:
        for field in form:
            data["-".join((form.prefix, field.name))] = field.value()

    self.client.post(reverse("/myview"), data, follow=True)

but I'm still wondering if there's a built-in formset method to do this, and I just can't see it....

Chris Curvey
  • 9,738
  • 10
  • 48
  • 70

1 Answers1

5

I have solved by passing following dict value in data

data = {
        # management_form data
        'form-INITIAL_FORMS': '0',
        'form-TOTAL_FORMS': '2',
        'form-MAX_NUM_FORMS': '',

         # First user data
        'form-0-username': 'addplayer1',
        'form-0-email': 'player1@addplayer.com',
        'form-0-password': 'admin',

        # Second user data
        'form-1-username': 'addplayer2',
        'form-1-email': 'player2@addplayer.com',
        'form-1-password': 'admin'
    }

    self.client.post(reverse("/myview"), data)
Subin Shrestha
  • 1,212
  • 11
  • 11
  • Also see [ManagementForm documentation](https://docs.djangoproject.com/en/3.1/topics/forms/formsets/#understanding-the-managementform) – djvg Sep 10 '20 at 18:01
  • It is also possible to build this `dict` automatically, based on a `get()` response. See examples here: https://stackoverflow.com/a/64354805 – djvg Oct 14 '20 at 14:01