How do I get user IP address in django?

后端 未结 11 1127
野趣味
野趣味 2020-11-22 15:33

How do I get user\'s IP in django?

I have a view like this:

# Create your views
from django.contrib.gis.utils import GeoIP
from django.template impor         


        
11条回答
  •  隐瞒了意图╮
    2020-11-22 16:16

    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
    

    Make sure you have reverse proxy (if any) configured correctly (e.g. mod_rpaf installed for Apache).

    Note: the above uses the first item in X-Forwarded-For, but you might want to use the last item (e.g., in the case of Heroku: Get client's real IP address on Heroku)

    And then just pass the request as argument to it;

    get_client_ip(request)
    

提交回复
热议问题