How to Get User Ip Address in Django

How do I get user IP address in Django?

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)

Django documentation for HttpRequest.META

Django : Get user IP from development server

Try this:

def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
print "returning FORWARDED_FOR"
ip = x_forwarded_for.split(',')[-1].strip()
elif request.META.get('HTTP_X_REAL_IP'):
print "returning REAL_IP"
ip = request.META.get('HTTP_X_REAL_IP')
else:
print "returning REMOTE_ADDR"
ip = request.META.get('REMOTE_ADDR')
return ip

Storing user's IP address in django's database on POST requests

Managed to make it work properly by changing views.py from.

if form.is_valid():
form.ip_address = get_client_ip(request)
form.save()

to.

if form.is_valid():
obj = form.save(commit=False)
obj.ip_address = get_client_ip(request)
obj.save()

and by editing the input field in my template.

For others who may read this, you should also take note of Kevin's comment, and exclude the ip_address field out of the form entirely instead of using hidden input in the template.

How to send user IP address from ListView to template?

get_context_data is not called with the request, it is an attribute of the view. You thus can access the request with self.request:

class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5

# no request ↓
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['ip'] = self.request.session.get('ip', 0)
return context

How do I get user IP address in Django?

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)

Django documentation for HttpRequest.META



Related Topics



Leave a reply



Submit