Romain Jouin
Romain Jouin

Reputation: 4838

Django how to add a pk to a request object?

I am struggling in my TDD to add a pk inside a request object in Django.

Here is my trial :

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

knowing that the info_Station take a pk as parameter :

def info_station(request, pk):

And my url file :

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

The error is :

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

How can I add this 'pk' parameter into my request ?

Upvotes: 2

Views: 1530

Answers (1)

Alasdair
Alasdair

Reputation: 308919

You don’t have to set pk on the request. You should pass it to the view as a separate argument, for example:

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

You may find RequestFactory useful for creating request objects in unit tests:

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

Or you may find it even easier to use the test client:

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

Upvotes: 4

Related Questions