def get_geoIP(request): # marseille = Point(5.3697800, 43.2964820) clermont = Point(3.0870250, 45.7772220) ip = request.META.get('REMOTE_ADDR', None) g = GeoIP(path=settings.PROJECT_PATH + '/config/GEO/') if ip and g.city(ip): return (Point(g.city(ip)['longitude'], g.city(ip)['latitude']), g.city(ip)['city']) else: return getattr(settings, 'DEFAULT_MAIN_CITY', (clermont, u'Clermont-Fd')) # default city
def test04_city(self): "Testing GeoIP city querying methods." g = GeoIP(country='<foo>') addr = '130.80.29.3' fqdn = 'chron.com' for query in (fqdn, addr): # Country queries should still work. for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name): self.assertEqual('US', func(query)) for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name): self.assertEqual('United States', func(query)) self.assertEqual( { 'country_code': 'US', 'country_name': 'United States' }, g.country(query)) # City information dictionary. d = g.city(query) self.assertEqual('USA', d['country_code3']) self.assertEqual('Houston', d['city']) self.assertEqual('TX', d['region']) self.assertEqual(713, d['area_code']) geom = g.geos(query) self.failIf(not isinstance(geom, GEOSGeometry)) lon, lat = (-95.3670, 29.7523) lat_lon = g.lat_lon(query) lat_lon = (lat_lon[1], lat_lon[0]) for tup in (geom.tuple, g.coords(query), g.lon_lat(query), lat_lon): self.assertAlmostEqual(lon, tup[0], 4) self.assertAlmostEqual(lat, tup[1], 4)
def cidade_index(request, cidade_slug): cidade = Cidade.objects.get(slug=cidade_slug) cidades_disponiveis = Cidade.objects.all() ofertas = Oferta.objects.filter(ativo=True) destaque = Oferta.objects.filter(cidade=cidade, destaque=True, ativo=True) #geoprocessamento ip_address = request.META.get('REMOTE_ADDR') g = GeoIP() #local_full_cliente = g.city(ip_address) local_full_cliente = g.city('201.22.164.216') cidade_cliente = local_full_cliente.get('city') print(cidade_cliente) if ofertas: try: oferta_estreia = ofertas.filter(estreando=True)[0] except IndexError: oferta_estreia = ofertas[0] outras_ofertas = ofertas.exclude(pk=oferta_estreia.pk) else: oferta_estreia = None outras_ofertas = [] return render_to_response( 'index.html', locals(), context_instance=RequestContext(request), )
def neighborhood_monitoring(request, template="geotagging/view_neighborhood_monitoring.html", content_type_name=None, distance_lt_km=None): """ Direct the user to a template that is able to render the `kml_neighborhood_feed` on a google map. This feed can be restricted based on the content type of the element you want to get. """ if distance_lt_km == None: distance_lt_km = 10 gip=GeoIP() if request.META["REMOTE_ADDR"] != "127.0.0.1": user_ip = request.META["REMOTE_ADDR"] else: user_ip = "populous.com" user_location_pnt = gip.geos(user_ip) kml_feed = reverse("geotagging-kml_neighborhood_feed", kwargs={"distance_lt_km":distance_lt_km}) criteria_pnt = { "point__distance_lt" : (user_location_pnt, D(km=float(distance_lt_km)) ) } geotag_points = Point.objects.filter(**criteria_pnt).distance(user_location_pnt).order_by("-distance") context = RequestContext(request, { "user_ip" : user_ip, "user_location_pnt" : user_location_pnt, "geotag_points" : geotag_points, "user_city" : gip.city(user_ip), "kml_feed" : kml_feed, }) return render_to_response(template,context_instance=context)
def test04_city(self): "Testing GeoIP city querying methods." g = GeoIP(country='<foo>') addr = '130.80.29.3' fqdn = 'chron.com' for query in (fqdn, addr): # Country queries should still work. for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name): self.assertEqual('US', func(query)) for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name): self.assertEqual('United States', func(query)) self.assertEqual({'country_code' : 'US', 'country_name' : 'United States'}, g.country(query)) # City information dictionary. d = g.city(query) self.assertEqual('USA', d['country_code3']) self.assertEqual('Houston', d['city']) self.assertEqual('TX', d['region']) self.assertEqual(713, d['area_code']) geom = g.geos(query) self.failIf(not isinstance(geom, GEOSGeometry)) lon, lat = (-95.3670, 29.7523) lat_lon = g.lat_lon(query) lat_lon = (lat_lon[1], lat_lon[0]) for tup in (geom.tuple, g.coords(query), g.lon_lat(query), lat_lon): self.assertAlmostEqual(lon, tup[0], 4) self.assertAlmostEqual(lat, tup[1], 4)
def location(request): """ Location selection of the user profile """ profile, created = Profile.objects.get_or_create(user=request.user) geoip = hasattr(settings, "GEOIP_PATH") if geoip and request.method == "GET" and request.GET.get('ip') == "1": from django.contrib.gis.utils import GeoIP g = GeoIP() c = g.city(request.META.get("REMOTE_ADDR")) if c and c.get("latitude") and c.get("longitude"): profile.latitude = "%.6f" % c.get("latitude") profile.longitude = "%.6f" % c.get("longitude") profile.country = c.get("country_code") profile.location = unicode(c.get("city"), "latin1") if request.method == "POST": form = LocationForm(request.POST, instance=profile) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("profile_edit_location_done")) else: form = LocationForm(instance=profile) template = "member/profile/location.html" data = { 'section': 'location', 'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY, 'form': form, 'geoip': geoip } return render_to_response(template, data, context_instance=RequestContext(request))
def location(request): """ Location selection of the user profile """ profile, created = Profile.objects.get_or_create(user=request.user) geoip = hasattr(settings, "GEOIP_PATH") if geoip and request.method == "GET" and request.GET.get("ip") == "1": from django.contrib.gis.utils import GeoIP g = GeoIP() c = g.city(request.META.get("REMOTE_ADDR")) if c and c.get("latitude") and c.get("longitude"): profile.latitude = "%.6f" % c.get("latitude") profile.longitude = "%.6f" % c.get("longitude") profile.country = c.get("country_code") profile.location = unicode(c.get("city"), "latin1") if request.method == "POST": form = LocationForm(request.POST, instance=profile) if form.is_valid(): form.save() request.user.message_set.create(message=_("Your profile information has been updated successfully.")) signal_responses = signals.post_signal.send(sender=location, request=request, form=form) last_reponse = signals.last_response(signal_responses) if last_reponse: return last_response else: form = LocationForm(instance=profile) template = "userprofile/profile/location.html" data = {"section": "location", "GOOGLE_MAPS_API_KEY": GOOGLE_MAPS_API_KEY, "form": form, "geoip": geoip} signals.context_signal.send(sender=location, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request))
def location(request): """ Location selection of the user profile """ profile = request.user.get_profile() geoip = hasattr(settings, "GEOIP_PATH") if geoip and request.method == "GET" and request.GET.get('ip') == "1": from django.contrib.gis.utils import GeoIP g = GeoIP() c = g.city(request.META.get("REMOTE_ADDR")) if c and c.get("latitude") and c.get("longitude"): profile.latitude = "%.6f" % c.get("latitude") profile.longitude = "%.6f" % c.get("longitude") profile.location = unicode(c.get("city"), "latin1") if request.method == "POST": form = UserLocationForm(request.POST, instance=profile) if form.is_valid(): form.save() messages.success(request, _("Your profile information has been updated successfully."), fail_silently=True) #signal_responses = signals.post_signal.send(sender=location, request=request, form=form) #last_response = signals.last_response(signal_responses) #if last_response: # return last_response else: form = UserLocationForm(instance=profile) #signals.context_signal.send(sender=location, request=request, context=data) return render_to_response("map/location_form_update.html", \ { 'GOOGLE_MAPS_API_KEY': settings.MAP_GOOGLE_MAPS_API_KEY, \ 'form': form, 'geoip': geoip }, context_instance=RequestContext(request))
def test04_city(self): "Testing GeoIP city querying methods." g = GeoIP(country="<foo>") addr = "130.80.29.3" fqdn = "chron.com" for query in (fqdn, addr): # Country queries should still work. for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name): self.assertEqual("US", func(query)) for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name): self.assertEqual("United States", func(query)) self.assertEqual({"country_code": "US", "country_name": "United States"}, g.country(query)) # City information dictionary. d = g.city(query) self.assertEqual("USA", d["country_code3"]) self.assertEqual("Houston", d["city"]) self.assertEqual("TX", d["region"]) self.assertEqual(713, d["area_code"]) geom = g.geos(query) self.failIf(not isinstance(geom, GEOSGeometry)) lon, lat = (-95.4152, 29.7755) lat_lon = g.lat_lon(query) lat_lon = (lat_lon[1], lat_lon[0]) for tup in (geom.tuple, g.coords(query), g.lon_lat(query), lat_lon): self.assertAlmostEqual(lon, tup[0], 4) self.assertAlmostEqual(lat, tup[1], 4)
def location(request): """ Location selection of the user profile """ profile, created = Profile.objects.get_or_create(user=request.user) geoip = hasattr(settings, "GEOIP_PATH") if geoip and request.method == "GET" and request.GET.get('ip') == "1": from django.contrib.gis.utils import GeoIP g = GeoIP() c = g.city(request.META.get("REMOTE_ADDR")) if c and c.get("latitude") and c.get("longitude"): profile.latitude = "%.6f" % c.get("latitude") profile.longitude = "%.6f" % c.get("longitude") profile.country = c.get("country_code") profile.location = unicode(c.get("city"), "latin1") if request.method == "POST": form = LocationForm(request.POST, instance=profile) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("profile_edit_location_done")) else: form = LocationForm(instance=profile) template = "member/profile/location.html" data = { 'section': 'location', 'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY, 'form': form, 'geoip': geoip } return render_to_response(template, data, context_instance=RequestContext(request))
def neighborhood_monitoring(request, template="geotags/view_neighborhood_monitoring.html", content_type_name=None, distance_lt_km=None): """ Direct the user to a template that is able to render the `kml_neighborhood_feed` on a google map. This feed can be restricted based on the content type of the element you want to get. """ if distance_lt_km == None: distance_lt_km = 10 gip=GeoIP() if request.META["REMOTE_ADDR"] != "127.0.0.1": user_ip = request.META["REMOTE_ADDR"] else: user_ip = "populous.com" user_location_pnt = gip.geos(user_ip) kml_feed = reverse("geotags-kml_neighborhood_feed", kwargs={"distance_lt_km":distance_lt_km}) criteria_pnt = { "point__distance_lt" : (user_location_pnt, D(km=float(distance_lt_km)) ) } geotag_points = Point.objects.filter(**criteria_pnt).distance(user_location_pnt).order_by("-distance") context = RequestContext(request, { "user_ip" : user_ip, "user_location_pnt" : user_location_pnt, "geotag_points" : geotag_points, "google_key" : settings.GOOGLE_MAPS_API_KEY, "user_city" : gip.city(user_ip), "kml_feed" : kml_feed, }) return render_to_response(template,context_instance=context)
def location(request): """ Location selection of the user profile """ profile, created = Profile.objects.get_or_create(user=request.user) geoip = hasattr(settings, "GEOIP_PATH") if geoip and request.method == "GET" and request.GET.get('ip') == "1": from django.contrib.gis.utils import GeoIP g = GeoIP() c = g.city(request.META.get("REMOTE_ADDR")) if c and c.get("latitude") and c.get("longitude"): profile.latitude = "%.6f" % c.get("latitude") profile.longitude = "%.6f" % c.get("longitude") profile.country = c.get("country_code") profile.location = unicode(c.get("city"), "latin1") if request.method == "POST": form = LocationForm(request.POST, instance=profile) if form.is_valid(): form.save() request.user.message_set.create(message=_("Your profile information has been updated successfully.")) signal_responses = signals.post_signal.send(sender=location, request=request, form=form) last_reponse = signals.last_response(signal_responses) if last_reponse: return last_response else: form = LocationForm(instance=profile) template = "userprofile/profile/location.html" data = { 'section': 'location', 'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY, 'form': form, 'geoip': geoip } signals.context_signal.send(sender=location, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request))
def create_gateway(sender, instance=None, created=False, **kwargs): """ create root domain of user """ if created: geo = GeoIP() data = geo.city(instance.ip) instance.city = data['city'] instance.country = data['country_name'] instance.save()
def get_local(ip): from django.contrib.gis.utils import GeoIP g = GeoIP() ip = request.META.get('REMOTE_ADDR', None) if ip: city = g.city(ip)['city'] else: city = 'Sao Paulo' # default city return city
def get_geoip_coords(request): lat, lng = '', '' geoip = GeoIP() # TODO: Middleware to set REMOTE_ADDR from HTTP_X_FORWARDED_FOR. remote_addr = get_remote_ip(request) geoip_result = geoip.city(remote_addr) if geoip_result: lat = geoip_result.get('latitude', '') lng = geoip_result.get('longitude', '') return lat, lng
def _cidade_cliente(request): #geo ip_address = request.META.get('REMOTE_ADDR') g = GeoIP() #local_full_cliente = g.city(ip_address) local_full_cliente = g.city('201.22.164.216') cidade_cliente = local_full_cliente.get('city') uni = cidade_cliente.decode('cp1252') cidade_cliente = uni.encode('utf8') return cidade_cliente
def getLocation(self): g = GeoIP() ip = request.META.get('REMOTE_ADDR',None) if ip: city = g.city(ip)['city'] return city else : print "nothing"
def whereami(request): g = GeoIP() remote_ip = request.META['REMOTE_ADDR'] if remote_ip == '127.0.0.1': remote_ip = get_my_ip() remote_location = g.city(remote_ip) if remote_location: return render_to_response('gmaps.html', {'remote_location': remote_location, 'GOOGLE_MAPS_API_KEY':settings.GOOGLE_MAPS_API_KEY}) else: # localhost ip cannot be found return render_to_response('not_found.html')
def _cidade_cliente(request): #geo ip_address=request.META.get('REMOTE_ADDR') g = GeoIP() #local_full_cliente = g.city(ip_address) local_full_cliente = g.city('201.22.164.216') cidade_cliente = local_full_cliente.get('city') uni = cidade_cliente.decode('cp1252') cidade_cliente = uni.encode('utf8') return cidade_cliente
def get_geoip_coords(request): lat, lng = '', '' geoip = GeoIP() # TODO: Middleware to set REMOTE_ADDR from HTTP_X_FORWARDED_FOR. remote_addr = get_remote_ip(request) geoip_result = geoip.city(remote_addr) if geoip_result: lat = geoip_result.get('latitude', '') lng = geoip_result.get('longitude', '') return lat, lng
def getLocation(self): g = GeoIP() ip = request.META.get("REMOTE_ADDR", None) if ip: city = g.city(ip)["city"] return city else: print "nothing"
def get_geo(video): latitude = 0.0 longitude = 0.0 g = GeoIP() if settings.GEOIP_PATH: try: data = g.city(video.job_set.all()[0].ip) if data: latitude = float(data['latitude']) longitude = float(data['longitude']) except StandardError, e: LOGGER.debug(str(e))
def process_request(self, request): request.LOCATION_DATA = False ip = request.META.get('HTTP_X_FORWARDED_FOR', '')\ or request.META.get('HTTP_X_REAL_IP', '')\ or request.META.get('REMOTE_ADDR', '') if ip: g = GeoIP() if settings.DEBUG: ip = '178.92.248.224' request.LOCATION_DATA = g.city(ip)
def whereis(request, ip): g = GeoIP() ip_match = re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b') try: remote_ip = ip_match.findall(ip)[0] except: remote_ip = '' remote_location = g.city(remote_ip) if remote_location: return render_to_response('gmaps.html', {'remote_location': remote_location, 'GOOGLE_MAPS_API_KEY':settings.GOOGLE_MAPS_API_KEY}) else: # localhost ip cannot be found return render_to_response('not_found.html')
def geoip_data(self): "Attempts to retrieve MaxMind GeoIP data based upon the visitor's IP" if not HAS_GEOIP or not TRACK_USING_GEOIP: return if not hasattr(self, '_geoip_data'): self._geoip_data = None try: gip = GeoIP(cache=GEOIP_CACHE_TYPE) self._geoip_data = gip.city(self.ip_address) except GeoIPException: log.error('Error getting GeoIP data for IP "%s": %s' % (self.ip_address, traceback.format_exc())) return self._geoip_data
def __init__(self, *args, **kwargs): if "request" in kwargs: self.request = kwargs["request"] del kwargs["request"] super(UserRegisterForm, self).__init__(*args, **kwargs) if "username" in self.base_fields: del self.base_fields["username"] del self.fields["username"] if hasattr(self, "request"): from django.contrib.gis.utils import GeoIP geoip = GeoIP() iso_city = (geoip.city(self.request.META.get("REMOTE_ADDR", "127.0.0.1")) or {}).get("city") city = get_object_or_None(City, iso__iexact=iso_city or "") if city: self.fields["city"].initial = city.pk
def find_location(self, ip): """ Pass in a dotted quad. first try the GeoIP db. If not there, fails to the db. This also catches the error in api is installed but settings not correct. """ ret_dict = {} try: g = GeoIP() # g = GeoIP() geolocation = g.city(ip) ret_dict["latitude"] = str(geolocation["latitude"]) ret_dict["longitude"] = str(geolocation["longitude"]) ret_dict["country_code"] = geolocation["country_code"] ret_dict["region"] = geolocation["region"] ret_dict["city"] = geolocation["city"] return ret_dict except: # didn't work so fall back to the db # print "Unexpected error:", sys.exc_info() try: lip = ip_to_long(ip) ret = Blocks.objects.filter(start__lte=lip).filter(end__gte=lip)[0] ret_dict["latitude"] = ret.loc.latitude ret_dict["longitude"] = ret.loc.longitude ret_dict["country_code"] = ret.loc.country ret_dict["region"] = ret.loc.region ret_dict["city"] = ret.loc.city ret_dict["postal_code"] = ret.loc.postal_code ret_dict["metro_code"] = ret.loc.metro_code ret_dict["area_code"] = ret.loc.area_code return ret_dict except: """ Danger Will Robinson !!!! Just bail. """ ret_dict["latitude"] = "25.0392" ret_dict["longitude"] = "121.5250" ret_dict["country_code"] = "TW" ret_dict["region"] = "03" ret_dict["city"] = "Taipei" return ret_dict
def _get_geoip_data(self): """ Attempts to retrieve MaxMind GeoIP data based upon the visitor's IP """ if not HAS_GEOIP or not USE_GEOIP: # go no further when we don't need to log.debug('Bailing out. HAS_GEOIP: %s; TRACKING_USE_GEOIP: %s' % (HAS_GEOIP, USE_GEOIP)) return None if not hasattr(self, '_geoip_data'): self._geoip_data = None try: gip = GeoIP(cache=CACHE_TYPE) self._geoip_data = gip.city(self.ip_address) except GeoIPException: # don't even bother... log.error('Error getting GeoIP data for IP "%s": %s' % (self.ip_address, traceback.format_exc())) return self._geoip_data
def _get_geoip_data(self): """ Attempts to retrieve MaxMind GeoIP data based upon the visitor's IP """ if not HAS_GEOIP or not USE_GEOIP: # go no further when we don't need to log.debug('Bailing out. HAS_GEOIP: %s; TRACKING_USE_GEOIP: %s' % (HAS_GEOIP, USE_GEOIP)) return None if not hasattr(self, '_geoip_data'): self._geoip_data = None try: gip = GeoIP(cache=CACHE_TYPE) self._geoip_data = gip.city(self.ip_address) except GeoIPException: # don't even bother... log.error('Error getting GeoIP data for IP "%s": %s' % (self.ip_address, traceback.format_exc())) return self._geoip_data
def set_redirect_by_ip(self, request): g = GeoIP() ip = get_real_ip(request) user_city = g.city(ip) target_city = None if user_city: target_city = get_object_or_None(City, name_by_geoip=user_city['city']) if not target_city: target_city = City.objects.get(is_default=True) target_domain = target_city.site.domain if not target_city.site.domain.startswith('http'): target_domain = 'http://%s' % target_domain target_url = urlparse(target_domain) request_url = urlparse('http://%s/' % request.get_host()) if not target_url.netloc == request_url.netloc: self.redirect_to = target_city.site.domain
def parse_data(self): self.parse_useragent() if self.ip: try: g = GeoIP() location = g.city(self.ip) if location: country = ox.get_country_name(location['country_code']) if location['city']: city = location['city'] if type(city) != unicode: city = city.decode('latin-1') self.location = u'%s, %s' % (city, country) self.location_sort = u'%s, %s' % (country, city) else: self.location_sort = self.location = country else: self.location_sort = self.location = None except: self.location_sort = self.location = None pass
def parse_data(self): self.parse_useragent() if self.ip: try: g = GeoIP() location = g.city(self.ip) if location: country = ox.get_country_name(location['country_code']) if location['city']: city = location['city'] if type(city) != unicode: city = city.decode('latin-1') self.location = u'%s, %s' % (city, country) self.location_sort = u'%s, %s' % (country, city) else: self.location_sort = self.location = country else: self.location_sort = self.location = None except: self.location_sort = self.location = None pass
def classifieds(request): """ Check the location of user for best guess and render classifieds template. """ user_ip = request.META.get('REMOTE_ADDR') #import ipdb; ipdb.set_trace() #user_ip = '68.48.6.208' # Check that user ip is valid if not either show all states, and cities # or handle it a different way g = GeoIP() user_location = g.city(user_ip) oodle = OodleAPI(num_results=15) location = 'San Fransisco' if user_location: #location = user_location['postal_code'] location = '%s, %s' % (user_location['city'], user_location['region']) oodle_api_url = oodle.build_url(location=location) try: total_results, posts = oodle.get_oodle_results(oodle_api_url) except OodleAPIException: return HttpResponseRedirect(reverse('about_signup')) # get all main categories categories_dict = {} """ root_categories = Category.objects.filter(is_root=True) for root_category in root_categories: categories_dict[root_category] = Category.objects.filter(is_root=False, url__contains=root_category.url) """ template_name = 'classifieds.html' return render_to_response(template_name, {'posts': posts, 'city': location, 'categories': categories_dict, 'user_ip': user_ip}, context_instance=RequestContext(request))
def process_request(self, request): user_agent = request.META['HTTP_USER_AGENT'].lower() os = OS["default"] for key, value in OS.items(): finder = user_agent.find(key.lower()) if finder > -1: os = OS[key] break browser = BROWSER["default"] for key, value in BROWSER.items(): finder = user_agent.find(key.lower()) if finder > -1: browser = BROWSER[key] break g = GeoIP() ip = request.META.get('REMOTE_ADDR', None) city = 'Unknow' if ip: try: city_data = g.city(ip) city = city_data.get('country_name', 'Unknow') except AttributeError: pass self.browser = browser self.geolocalization = city self.plataform = os return { "plataform": self.plataform, "browser": self.browser, "geolocalization": self.geolocalization, }
def catalog_list(request, service_pk=0, codename='', is_special=False): service = ( get_object_or_None(Service, pk=service_pk) or get_object_or_None(Service, codename=codename) ) search_type = request.GET.get('search-type', 0) is_special = request.GET.get('is_special', is_special) cardpay = request.GET.get('cardpay', False) # container_list = request.GET.getlist('type') or None categories_list = request.GET.getlist('type', []) categories_list = categories_list if all(categories_list) else [] minimal_cost = request.GET.get('minimal_cost', 0) title = request.GET.get('title', '') by_rating = request.GET.get('by_rating', False) nlat, mlat, nlng, mlng = map(request.GET.get, ['nlat', 'mlat', 'nlng', 'mlng']) free_deliver = request.GET.get('free_deliver', False) state = request.GET.get('state', 1) if not service: raise Http404("No such service found") # select only that cities where user is bind to geoip = GeoIP() ip = request.GET.get('REMOTE_ADDR', '127.0.0.1') city = request.session.get( 'city', request.user.city if request.user.is_authenticated() else \ (geoip.city(ip) or {}).get('city', None) ) owners_ids = [id_dict.values()[0] for id_dict in User.objects.filter(is_published=True).values('id')] containers = Container.objects.select_related('owner').filter( service=service, owner__in=owners_ids).order_by('owner') #@TODO: select_related state = int(state) if isinstance(state, basestring) else 1 if state: now = datetime.now().replace(second=0, microsecond=0) week_day = now.isoweekday() prev_week_day = week_day - 1 if week_day > 1 else 7 qset = ( # since < until Q(until__gte=now, since__lte=now, weekday=week_day) | # since > until (Q(until__lt=F('since')) & Q(since__lte=now, weekday=week_day)) | # next day jump (Q(until__lt=F('since')) & Q(until__gte=now, weekday=prev_week_day)) ) td = TimeNDay.objects.filter( Q(is_active=True) & qset ) schedules = Schedule.objects.filter(timenday_schedule_set__in=td) containers = containers.filter(owner__schedule_user_set__in=schedules) if by_rating: containers = containers.order_by('-mean_rating') if city: containers = containers.filter(owner__city=city) else: top_city = City.objects.all()[0] containers = containers.filter(owner__city=top_city) if free_deliver: containers = containers.exclude(owner__avarage_cost=None) # containers = containers.filter(owner__avarage_deliver_cost=0) unique_containers = containers.filter( container=None).order_by('title').distinct('title') if categories_list: categories = Category.objects.filter(pk__in=categories_list) categories = categories | \ Category.objects.filter(parent__in=categories) # 2 lvl categories = categories | \ Category.objects.filter(parent__in=categories) # 3 lvl containers = containers. \ filter(category__in=categories) # categories_list) # containers = ( # containers.filter(container__title__in=container_list) | # containers.filter(title__in=container_list) # ) if isinstance(minimal_cost, basestring): minimal_cost = int(minimal_cost) if minimal_cost.isdigit() else 0 if minimal_cost: # owner__avarage_cost__lte=minimal_cost) containers = containers.filter(owner__minimal_cost__lte=minimal_cost) if cardpay: containers = containers.exclude(owner__has_online_payment=False) if all((nlat, mlat, nlng, mlng)): positions = GPos.objects.filter( lat__gte=nlat, lat__lte=mlat, lng__gte=nlng, lng__lte=mlng ) containers = containers.filter(owner__gpos_user_set__in=positions) # containers = ( # containers.filter( # owner__glat__gte=nlat, owner__glat__lte=mlat, # owner__glng__gte=nlng, owner__glng__lte=mlng # ) # ) has_coords = 'nlat' in request.GET has_coords = has_coords and 'mlat' in request.GET has_coords = has_coords and 'nlng' in request.GET has_coords = has_coords and 'mlng' in request.GET if has_coords and not all((nlat, mlat, nlng, mlng)): containers = Container.objects.filter(id=-1) items = Item.objects.filter(container__in=containers) new_ones = request.GET.get('new_ones', False) one_week = datetime.now() - timedelta(weeks=1) if search_type == '1': # by items items = items.filter( title__icontains=title ) if new_ones: items = items.filter(container__owner__publish_date__gte=one_week) if is_special: items = items.filter(is_special_active=True) else: # by containers containers = containers.filter( owner__service_name__icontains=title).order_by( 'owner').distinct('owner') if new_ones: containers = containers.filter(owner__publish_date__gte=one_week) if is_special: items = Item.objects.filter(is_special_active=True, container__service=service) pks = containers.exclude(owner__special_owner_set=None) containers = ( Container.objects.filter(item_container_set__in=items) | Container.objects.filter(pk__in=pks) ) if by_rating: containers = containers.order_by('-mean_rating') # containers = containers.filter(item_container_set__in=items) page = request.GET.get('page', 1) containers = Container.objects.filter( pk__in=containers).distinct().order_by('-mean_rating').distinct() categories = Category.objects.filter(service=service) # ordering items = Item.objects.filter( pk__in=items.order_by('-cost').values('pk') ).distinct().order_by('-cost') order_by = request.GET.get('order_by', '-cost') order_by_asc = not order_by.startswith('-') if not order_by_asc: order_by = order_by[1:] order_by_prefix = '-' order_by_prefix_future = '' else: order_by_prefix = '' order_by_prefix_future = '-' if order_by in settings.CATALOG_ORDER_BY: items = items.order_by(order_by_prefix + order_by) if by_rating: items = items.order_by('-container__mean_rating') # paging containers = paginate(containers, page, pages=settings.DEFAULT_PAGES_COUNT) items = paginate(items, page, pages=settings.DEFAULT_PAGES_COUNT) dt = { 'service': service, 'categories': categories, 'containers': containers, 'items': items, 'unique_containers': unique_containers, 'search_type': search_type, 'types': [int(i if i.isdigit() else 0) for i in request.GET.getlist('type')], 'G': request.GET, # 'request': request, 'order_by': order_by, 'order_by_prefix': order_by_prefix, 'order_by_prefix_future': order_by_prefix_future, } if settings.SAUSAGE_SCROLL_ENABLE: if int(search_type) == 1 and int(page) != 1: dt.update({'_template': 'catalog/include/items.html'}) elif int(page) != 1: dt.update({"_template": "catalog/include/partners.html"}) return dt
from django.contrib.gis.utils import GeoIP g = GeoIP() ip = request.META.get('REMOTE_ADDR', None) if ip: city = g.city(ip)['city'] else: city = 'Rome' # default city # proceed with city
def get_geoip(self): g = GeoIP() return g.city(self.get_ip(force_wanip = True))
def get_point(ip): g = GeoIP() remote_location = g.city(ip) point = 'POINT(%(lon)s %(lat)s)' return point % {'lon': remote_location['longitude'], 'lat': remote_location['latitude']}