首页 > 解决方案 > 如何在测试期间将参数传递给请求?

问题描述

我通过 Client() 运行测试。post,但 request.POST 不包含传递的字典

测试.py

from django.test import TestCase
from django.test.client import Client

class AccountTests(TestCase):

    def setUp(self):
        self.email = 's@s/com'
        self.name = 'John'
        self.mobile = "+799999999"

    def test_user_login(self):
        c = Client()
        response = c.post('/login-otp/',
                          {'email': self.email, 'name': self.name, 'mobile': self.mobile},
                          follow=True)

视图.py

def login_otp(request):
    mobile = request.session['mobile'] # the interpreter does not see the "mobile" key
    context = {'mobile': mobile}
    if request.method == 'POST':
        otp = request.POST.get('otp')

标签: pythondjangodjango-views

解决方案


您没有mobile作为 POST 参数传递。

试试这个:

def login_otp(request):
    mobile = request.POST['mobile']
    ...

编辑:

您可以像这样设置会话变量:https ://docs.djangoproject.com/en/3.0/topics/testing/tools/#django.test.Client.session


推荐阅读