Django如何将pk添加到请求对象?

时间:2017-11-28 23:08:28

标签: python django request

我在TDD中苦苦挣扎,在Django的请求对象中添加一个pk。

这是我的试用版:

request             = HttpRequest()
request.method      = "GET"
request.GET         = request.GET.copy()
request.GET["pk"]   =  1
response            = info_station(request)

知道info_Station将pk作为参数:

def info_station(request, pk):

我的网址文件:

url(r'^info_station/(?P<pk>[0-9]+)$', views.info_station)

错误是:

info_station() missing 1 required positional argument: 'pk'

我该如何添加这个&#39; pk&#39;参数进入我的请求?

1 个答案:

答案 0 :(得分:3)

您不必在请求中设置pk。您应该将其作为单独的参数传递给视图,例如:

request = HttpRequest()
request.method = "GET"
response = info_station(request, pk=1)

您可能会发现RequestFactory对于在单元测试中创建请求对象很有用:

from django.test import RequestFactory
factory = RequestFactory()
request = self.factory.get('/info_station/1')
response = info_station(request, pk=1)

或者您可能会发现使用test client

更加容易
from django.test import Client
client = Client()
response = client.get('/info_station/1')