gpt4 book ai didi

django-testing - 如何测试 Django 表单集提交

转载 作者:行者123 更新时间:2023-12-02 20:41:36 26 4
gpt4 key购买 nike

我要么错过了一些非常简单的东西(并且我的 Google-Fu 缺失),要么我偏离了轨道。您调用电话!

我想编写一个测试来练习将表单集发布到 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'

这个错误是完全有道理的,因为我需要传递一个字典作为第二个参数,而不是一个表单集。我希望 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)

但我仍然想知道是否有内置的表单集方法可以做到这一点,但我只是看不到它......

最佳答案

我已经通过在数据中传递以下字典值来解决

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': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="542438352d312665143530302438352d31267a373b39" rel="noreferrer noopener nofollow">[email protected]</a>',
'form-0-password': 'admin',

# Second user data
'form-1-username': 'addplayer2',
'form-1-email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a7a666b736f78384a6b6e6e7a666b736f7824696567" rel="noreferrer noopener nofollow">[email protected]</a>',
'form-1-password': 'admin'
}

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

关于django-testing - 如何测试 Django 表单集提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45984882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com