如何测试Django formset提交

时间:2017-08-31 15:16:26

标签: django-testing

我要么缺少一些非常简单的东西(我的Google-Fu缺乏),要么我偏离轨道。你打电话了!

我想编写一个测试来将一个formset发布到视图中。

# 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'

错误很有意义,因为我需要将字典作为第二个参数传递,而不是Formset。我希望Formset上有一些方法可以给我一个合适的字典(带有管理表单信息),但是我找不到它的生命。

更新:

我通过这样做得到了它:

    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)

但我仍然想知道是否有一个内置的formset方法来做到这一点,我只是看不到它....

1 个答案:

答案 0 :(得分:0)

我通过在数据中传递以下dict值来解决

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)