Django 测试 - 获取初始值并将其反馈回来

发布于 2024-12-27 09:24:05 字数 1168 浏览 0 评论 0原文

我有一个引用ForeignKeys 和ManyToMany 对象的基本模型。在“编辑”测试中,您获取视图的 id 并对其进行更改,我遇到了一个问题,我很好奇是否有其他人找到了更干净的解决方法。我发现 这篇 帖子让我开始沮丧正确的道路

    client = Client()
    response = client.get(reverse("floorplan_update", kwargs={'pk': floorplan.id}))

    data = response.context['form'].initial

    # Ideally you should be able to do this..
    response = client.post(reverse("floorplan_update", kwargs={'pk': floorplan.id}),
                           data=data, follow=True)

,但你不能这样做。如果你有 FK 或 M2M,你需要首先做这个丑陋的事情......

    client = Client()
    response = client.get(reverse("floorplan_update", kwargs={'pk': floorplan.id}))

    data = response.context['form'].initial

    # Ugliness ensues..
    data['document'] = open(__file__)
    data['company']= data['company'].id
    data['target']= data['target'].id

    # Only now can you post..

    response = client.post(reverse("floorplan_update", kwargs={'pk': floorplan.id}),
                           data=data, follow=True)

还有其他人遇到过这个吗?或者有更好的方法来处理这个吗?

I have a basic model which references both ForeignKeys and ManyToMany objects. In "edit" testing where you are taking the id of a view and making changes to it I ran into a problem and I'm curious if anyone else figured out a cleaner workaround. I found this post which started me down the right path

    client = Client()
    response = client.get(reverse("floorplan_update", kwargs={'pk': floorplan.id}))

    data = response.context['form'].initial

    # Ideally you should be able to do this..
    response = client.post(reverse("floorplan_update", kwargs={'pk': floorplan.id}),
                           data=data, follow=True)

But you can't do this. In cases where you have FK's or M2M's you need to first do this ugliness...

    client = Client()
    response = client.get(reverse("floorplan_update", kwargs={'pk': floorplan.id}))

    data = response.context['form'].initial

    # Ugliness ensues..
    data['document'] = open(__file__)
    data['company']= data['company'].id
    data['target']= data['target'].id

    # Only now can you post..

    response = client.post(reverse("floorplan_update", kwargs={'pk': floorplan.id}),
                           data=data, follow=True)

Has anyone else ran into this or is there a better way to deal with this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

↙温凉少女 2025-01-03 09:24:05

不确定,但你可以尝试这个:

data = response.context['form'].instance.__dict__

Not sure, but you can try this instead:

data = response.context['form'].instance.__dict__
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文