[Fixed]-Setting HTTP_REFERER header in Django test

29👍

Almost right. It’s actually:

def transaction_status_suceeds(self):
    response = self.client.post(reverse('transaction_status'), {}, HTTP_REFERER='http://foo/bar')

I’d missed a ** (scatter operator / keyword argument unpacking operator / whatever) when reading the source of test/client.py; extra ends up being a dictionary of extra keyword arguments to the function itself.

5👍

You can pass HTTP headers to the constructor of Client:

from django.test import Client
from django.urls import reverse

client = Client(
    HTTP_USER_AGENT='Mozilla/5.0',
    HTTP_REFERER='http://www.google.com',
)
response1 = client.get(reverse('foo'))
response2 = client.get(reverse('bar'))

This way you don’t need to pass headers every time you make a request.

Leave a comment