I am using Django and need to get the user's current location, so I use geocoder.ip('me')
. It works fine locally, but after I deploy it on Heroku, it seems like it's not working. Is that because the IP address or something like that? How can I fix it? Or is there any way else that is easier for me to access user current location in views.py? Thank you.
I found the way to get the ip address in How do I get user IP address in django?, but I don't know how to really get the ip address so that I can use it in other part of the code.
def get_client_ip(self,request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
class RecommendView(generic.ListView):
template_name = 'event/recommend.html'
context_object_name = 'recommend_event_list'
today = datetime.now().date()
end = today + timedelta(7)
time_start = datetime.combine(today, time())
time_end = datetime.combine(end, time())
ip = get_client_ip()
myloc = geocoder.ip(ip,key='my_key')
def get_queryset(self):
rec=Event.objects.filter(post_date__range=(self.time_start, self.time_end))
for event in rec:
g = geocoder.mapbox(event.address, key='my_key')
R = 6373.0
lat1 = math.radians(self.myloc.lat)
lon1 = math.radians(self.myloc.lng)
lat2 = math.radians(g.lat)
lon2 = math.radians(g.lng)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
dis = R * c
if dis>20:
rec=rec.exclude(address=event.address)
return rec.order_by('-post_date')