Django (v4) request.META['REMOTE_ADDR'] not working anymore?
I had been using for years (Django 1.9 & Python 2.7)
request.META dictionary and
['REMOTE_ADDR'] header to get client's IP address.
I have recently moved to Django 4.1.5 and found out that my code is not able anymore to get client's IP address, so I had to use:
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',') else: ip = request.META.get('REMOTE_ADDR') return ip
which works fine.
I've tested my old code in development mode and tried to log
request.META.get('REMOTE_ADDR'). The code will log IP only if the IP address is localhost (127.0.0.1). With any other IP address,
REMOTE_ADDR header stays blank.
I'm just curious, could someone tell me why this is happening?
Check your intermediate proxies like nginx, apache, etc if you use one in between of your requests and web application. sometimes proxies manipulate request headers before sending it to web application
for instance for Nginx you could use something like this (source):
proxy_set_header X-Forwarded-For $remote_addr;