Home  >  Article  >  Backend Development  >  How to Get a User's IP Address in Django?

How to Get a User's IP Address in Django?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-05 07:45:02636browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn