Home >Backend Development >Python Tutorial >How to Get a User's IP Address in Django?
Obtain User IP Address in Django
In order to retrieve the user's IP address in Django, customize it by creating a reusable utility function:
<code class="python">def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip</code>
Note that this function first checks for the X-Forwarded-For header, which is used by reverse proxies to indicate the client's original IP address. If this header is present, it uses the first IP address from the comma-separated list. Otherwise, it falls back to REMOTE_ADDR.
Once you have defined this function, you can obtain the user's IP address as follows:
<code class="python">ip = get_client_ip(request)</code>
The above is the detailed content of How to Get a User's IP Address in Django?. For more information, please follow other related articles on the PHP Chinese website!