在Django测试期间,如何通过客户端将帖子的ID传递给帖子?

发布于 2025-02-10 07:19:12 字数 767 浏览 0 评论 0原文

def test_sharing_post_through_email(self):
        form = {'name': 'Martin', 'email': '[email protected]', 'to': '[email protected]'}
        
        response = self.client.post('/<int:id>/share/', data={'post': self.post, 'form': form})
        response.user = self.user

        self.assertEqual(response.status_code, 200)
        self.assertIsInstance(response.context, dict)
        self.assertEqual(response.context['sent'], True)

如何将ID传递给那里的URL?

def test_sharing_post_through_email(self):
        form = {'name': 'Martin', 'email': '[email protected]', 'to': '[email protected]'}
        
        response = self.client.post('/<int:id>/share/', data={'post': self.post, 'form': form})
        response.user = self.user

        self.assertEqual(response.status_code, 200)
        self.assertIsInstance(response.context, dict)
        self.assertEqual(response.context['sent'], True)

how can I pass the ID to the url there?

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

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

发布评论

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

评论(1

等风来 2025-02-17 07:19:12

您应该从django.urls使用反向。让我们在urls.py as中定义您的URL,as:

path('/<int:id>/share/', views.share_view, name="share_view")

您可以以相反的方式传递 id

from django.urls import reverse

def test_sharing(self):
    url = reverse("share_view", kwargs={"id": 1234})
    response = self.client.post(url, data={"post": "1"})

您必须在反向调用中使用该应用程序名称。如果您的目标视图在应用程序“主页”中:

url = reverse("home:share_view", kwargs={"id": 1234})

You should use reverse from django.urls. Lets supose your url is defined in urls.py as:

path('/<int:id>/share/', views.share_view, name="share_view")

You could pass the id with reverse as:

from django.urls import reverse

def test_sharing(self):
    url = reverse("share_view", kwargs={"id": 1234})
    response = self.client.post(url, data={"post": "1"})

You'll have to use the app name in the reverse calling. If your targeted view is in the app "home":

url = reverse("home:share_view", kwargs={"id": 1234})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文