R
R
Ruslan Ezhgurov2015-11-13 21:39:40
Django
Ruslan Ezhgurov, 2015-11-13 21:39:40

How to get user's ip in Django project?

Good evening, I'm not doing a big project, you need to save the user's ip, the project is distributed at 127.0.0.1 and in nginx it is already redirected to the server address. Used info from Django documentation .

ip = request.META.get('REMOTE_ADDR', '') or request.META.get('HTTP_X_FORWARDED_FOR', '')  
user.user_ip=ip
user.save()

As a result, I get in the User.user_ip field - 127.0.0.1
What is wrong, please tell me?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
un1t, 2015-11-13
@Oyaseo

In nginx, forward the client's ip:
proxy_set_header X-Real-IP $remote_addr;
or
uwsgi_param X-Real-IP $remote_addr;
In Djang get:
request.META['HTTP_X_REAL_IP']

A
Artem Afonin, 2015-12-10
@reli

Works without nginx:

class UpdateIPv4UserMeta(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        user = request.user
        today_30min = timezone.now() + timezone.timedelta(minutes=30)
        if user.is_authenticated():
            if user.last_login > today_30min:
                User.objects.filter(id=request.user.id).\
                    update(latest_ip=request.META['REMOTE_ADDR'])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question