andy
andy

Reputation: 1459

Django autogenerate POST data dict for arbitrary admin form

I would like to autogenerate a dictionary of data to POST to a django admin change form, as if the current object is not changing. Basically simulate the POST request that would happen if you do a GET on the change page from the admin, and then click Save. This should take into account which fields are editable on that particular change form, and also be able to handle InlineAdmins.

    def auto_generate_changeform_data(object):
        data = ???
        return data

For example, in line 302 of the django admin testcases they manually create the POST data dictionary, but this is something that should be possible to autogenerate, right?

I would then use this function in a testcase where I want to test what happens when I change one particular field on that model, or even one of the inlines.

    #some testcase
    some_object = SomeModel.objects.get(...)
    url = reverse("admin:appname_modelname_change", args=[some_object.id])
    data = auto_generate_changeform_data(some_object)
    data['some_field'] = 'new value'  #this is the only change I want to make
    response = self.client.post(url, data)

I could do all of this in a more unit-y fashion by using the methods on the ModelAdmin class instead of going through a POST request to the client, but I want a functional test not a unit test in this case. I actually do want to simulate the full POST to the url.

How can I get this data dictionary, particularly the part about inline formsets?

Upvotes: 1

Views: 258

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599796

I've done this before by simply doing the GET request with the test client and then using BeautifulSoup to scrape out all the input and select elements.

It's not completely straightforward because of the different ways those elements represent their values, but here is some code that should work.

Upvotes: 1

Related Questions