[Django]-How to specify an IP address with Django test client?

33👍

The Client.get() method has an extra keyword arguments parameter, which can be used to specify headers.

c.get(/my-url/, REMOTE_ADDR="127.0.0.1") 

11👍

Pass REMOTE_ADDR in constructor.

client = HttpClient(REMOTE_ADDR='127.0.0.1')

or

client.get('/path/', {'param':'foo'}, **{'HTTP_USER_AGENT':'firefox-22', 'REMOTE_ADDR':'127.0.0.1'})

3👍

You can also set it for all future requests:

client.defaults['REMOTE_ADDR'] = '1.2.3.4'

Also with subclassing:

class DecoratedApiClient(Client):
    def set_ip_addr(self, ip_addr):
        self.defaults['REMOTE_ADDR'] = ip_addr

client = DecoratedApiClient()
client.set_ip_addr('1.2.3.4')
👤gak

-2👍

As simple like this:

client_address = request.META.get('HTTP_X_FORWARDED_FOR') or request.META.get('REMOTE_ADDR')

Leave a comment