def count_by_country(self): geoip = GeoIP() count = Counter() for request in self.all(): if request.ip is None or geoip.country_code(request.ip) is None: continue country = geoip.country(request.ip) count[country['country_code']] += 1 return count
def test01_init(self): "GeoIP initialization." g1 = GeoIP2() # Everything inferred from GeoIP path path = settings.GEOIP_PATH g2 = GeoIP2(path, 0) # Passing in data path explicitly. g3 = GeoIP2.open(path, 0) # MaxMind Python API syntax. for g in (g1, g2, g3): self.assertTrue(g._country) self.assertTrue(g._city) # Only passing in the location of one database. city = os.path.join(path, 'GeoLite2-City.mmdb') cntry = os.path.join(path, 'GeoLite2-Country.mmdb') g4 = GeoIP2(city, country='') self.assertIsNone(g4._country) g5 = GeoIP2(cntry, city='') self.assertIsNone(g5._city) # Improper parameters. bad_params = (23, 'foo', 15.23) for bad in bad_params: with self.assertRaises(GeoIP2Exception): GeoIP2(cache=bad) if isinstance(bad, str): e = GeoIP2Exception else: e = TypeError with self.assertRaises(e): GeoIP2(bad, 0)
def map_home(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') g = GeoIP2() (lat, lng) = g.lat_lon(ip) # lat = 19.0748 # lng = 72.8856 pnt = Point(lng, lat, srid=4326) inc_near = Incidences.objects.annotate( distance=Distance('location', pnt)).order_by('distance').first() # print(inc_near) # name = Incidences.objects.filter('name' == inc_near) string = str(inc_near.location) near_lat = "" near_lng = "" take1 = True go = False for i in string: if i == '(': go = True continue if i == ')': break if go: if i == " ": take1 = False elif take1: near_lng += i else: near_lat += i all_incidences = Incidences.objects.all() context = { 'lng': lng, 'lat': lat, 'near_lat': near_lat, 'near_lng': near_lng, 'all_incidences': all_incidences, } return render(request, 'geo/index.html', context)
def get_user_location(request): """ This function captures the user's IP Address, User-Agent, Country and City """ values = {} # Get IP Address of user try: x_forward = request.META.get("HTTP_X_FORWARDED_FOR") if x_forward: ip = x_forward.split(",")[0] else: ip = request.META.get("REMOTE_ADDR") except: ip = "" # Get User Agent of user try: user_agent = request.META.get("HTTP_USER_AGENT") except: user_agent = "" # Trace user location using Geoip API from django.contrib.gis.geoip2 import GeoIP2 g = GeoIP2() # Get Country of user try: country = g.country_name(ip) except: country = "" # Get City of user try: city = g.city(ip)['city'] except: city = "" values['ip'] = ip values['user_agent'] = user_agent values['country'] = country values['city'] = city return values
def store_search(request): # https://docs.djangoproject.com/en/2.2/ref/contrib/gis/geoip2/# # https://github.com/un33k/django-ipware # https://developers.google.com/maps/documentation/urls/guide # dev_ip = 'www.hamburg.de' # for use during development, Hamburg Germany dev_ip = '2a02:8108:4640:1214:b9e5:9090:525c:d282' # Get client ip address client_ip, is_routable = get_client_ip(request) if client_ip is None: found_ip = dev_ip else: # We got the client's IP address if is_routable: found_ip = client_ip else: #found_ip = 'Your IP is private' found_ip = dev_ip # Get location from IP address g = GeoIP2() city = g.city(found_ip) lat, lon = g.lat_lon(found_ip) # Have a bit of fun #lat, lon, city['city'], city['country_name'] = 51.5074, 0.1278, 'London', 'UK' #lat, lon, city['city'], city['country_name'] = 43.6532, -79.3832, 'Toronto', 'Canada' #lat, lon, city['city'], city['country_name'] = 48.8566, 2.3522, 'Paris', 'France' #lat, lon, city['city'], city['country_name'] = 53.3498, -6.2603, 'Dublin', 'Ireland' user_location = Point(lon, lat, srid=4326) # Filter stores by distance results = Store.objects.annotate( distance=Distance('location', user_location)) results = results.order_by('distance')[:100] context = {'city': city['city'], 'country': city['country_name'], 'store_list': results} return render(request, 'stores/search_results.html', context)
def __call__(self, request): if "HTTP_X_FORWARDED_FOR" in request.META: request.META["HTTP_X_PROXY_REMOTE_ADDR"] = request.META[ "REMOTE_ADDR"] parts = request.META["HTTP_X_FORWARDED_FOR"].split(",", 1) request.META["REMOTE_ADDR"] = parts[0] ip = request.META["REMOTE_ADDR"] g = GeoIP2() try: ip_response = g.city(ip) time_zone = ip_response['time_zone'] except AddressNotFoundError: time_zone = None if time_zone: timezone_object = pytz.timezone(time_zone) timezone.activate(timezone_object) else: timezone.deactivate() return self.get_response(request)
def get(self, request, format=None): from django.contrib.gis.geoip2 import GeoIP2 import os from backend.settings import BASE_DIR from ipware import get_client_ip g = GeoIP2(path=os.path.join(BASE_DIR, 'api', 'geoipdata')) ip, is_routable = get_client_ip(request) if ip is None: return Response({"country": "Unknown", "ip": None}) else: if is_routable: return Response({ "country": g.country(ip)['country_name'], "ip": ip }) else: return Response({"country": "Private", "ip": ip})
def test_repr(self): path = settings.GEOIP_PATH g = GeoIP2(path=path) meta = g._reader.metadata() version = "%s.%s" % ( meta.binary_format_major_version, meta.binary_format_minor_version, ) country_path = g._country_file city_path = g._city_file expected = ( '<GeoIP2 [v%(version)s] _country_file="%(country)s", _city_file="%(city)s">' % { "version": version, "country": country_path, "city": city_path, } ) self.assertEqual(repr(g), expected)
def fetch(request): geo_ip = GeoIP2() # client_ip = request.META.get('REMOTE_ADDR') client_ip = '77.47.236.2' try: city = City.objects.get(name=geo_ip.city(client_ip)['city']) if city.date_update.date() != timezone.now().date(): city.delete() city = create_models(geo_ip, client_ip) except City.DoesNotExist: city = create_models(geo_ip, client_ip) except AddressNotFoundError: args = dict() args['error_message'] = 'Your address was not found' return render_to_response('openweathermap/index.htm', args) args = dict() args['city'] = city return render_to_response('openweathermap/index.htm', args)
def paygol_ipn(request): ip = get_ip(request) g = GeoIP2() try: country = g.country(ip) if country["country_name"] == "Georgia": user_language = 'ka_GE' translation.activate(user_language) response = HttpResponse() response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language) elif country["country_name"] == "Russia" or country[ "country_name"] == "Ukraine" or country[ "country_name"] == "Belarus" or country[ "country_name"] == "Latvia" or country[ "country_name"] == "Lithuania" or country[ "country_name"] == "Moldova" or country[ "country_name"] == "Estonia": user_language = 'ru' translation.activate(user_language) response = HttpResponse() response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language) except: pass secret_key = "14846f31-426a-11e8-b407-128b57940774" if secret_key != request.GET.get('key'): return HttpResponseRedirect("/cabinet") transaction_id = request.GET.get('transaction_id') service_id = request.GET.get('service_id') shortcode = request.GET.get('shortcode') keyword = request.GET.get('keyword') message = request.GET.get('message') sender = request.GET.get('sender') operator = request.GET.get('operator') country = request.GET.get('country') custom = request.GET.get('custom') price = request.GET.get('frmprice') currency = request.GET.get('currency') balance = MyProfile.objects.get(user_id=custom) finalprice = Decimal(price) balance.account_balance += finalprice balance.save() return HttpResponseRedirect("/")
def home_page(request): ### popup that presents rules. g = GeoIP2() ip = get_client_ip(request) try: lat, lng = g.lat_lon(ip) city = g.city(ip) place = city['city'] + ', ' + city['country_name'] except: lat, lng = -7.480207, 178.675933 place = "Tuvalu" success = "We can't find your location so your photo will be posted to the Island Nation of Tuvalu" photos = Photo.objects.all().order_by('timestamp')[:60][::-1] for photo in photos: lon2 = photo.lon lat2 = photo.lat uuid = photo.uuid getPhotos = PhotoViewSet() photo.distance = getPhotos.haversine(lng, lat, lon2, lat2) return render(request, 'home.html', {'photos': photos, 'place': place})
def test03_country(self): "GeoIP country querying methods." g = GeoIP2(city='<foo>') for query in (self.fqdn, self.addr): self.assertEqual( 'US', g.country_code(query), 'Failed for func country_code and query %s' % query ) self.assertEqual( 'United States', g.country_name(query), 'Failed for func country_name and query %s' % query ) self.assertEqual( {'country_code': 'US', 'country_name': 'United States'}, g.country(query) )
def home(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') device_type = "" browser_type = "" browser_version = "" os_type = "" os_version = "" if request.user_agent.is_mobile: device_type = "Mobile" if request.user_agent.is_tablet: device_type = "Tablet" if request.user_agent.is_pc: device_type = "PC" browser_type = request.user_agent.browser.family browser_version = request.user_agent.browser.version_string os_type = request.user_agent.os.family os_version = request.user_agent.os.version_string g = GeoIP2() location = g.city(ip) location_country = location["country_name"] location_city = location["city"] context = { "ip": ip, "device_type": device_type, "browser_type": browser_type, "browser_version": browser_version, "os_type":os_type, "os_version":os_version, "location_country": location_country, "location_city": location_city } return render(request, "home.html", context)
def get(self, request): resp_dict = { 'login_error': request.GET.get('login_error', 0), 'page': 'single', 'org_types': OrganizationType.objects.all() .prefetch_related("claimtype_set").order_by('name'), 'test_alarm': False} claim_type_sets = {} for org_type in resp_dict['org_types']: claim_type_set = [] for claim_type in org_type.claimtype_set.all(): claim_type_set.append({'id': claim_type.id, 'value': claim_type.name}) claim_type_sets[org_type.type_id] = claim_type_set resp_dict['claim_types'] = mark_safe(json.dumps(claim_type_sets)) if settings.RECAPTCHA_ENABLED is False: settings.RECAPTCHA_PUBLIC = '' resp_dict['recaptcha_public'] = settings.RECAPTCHA_PUBLIC if settings.TEST_SERVER: resp_dict['test_alarm'] = True ip = get_client_ip(request) # cached_zoom = cache.get('lat_lon_for::%s' % ip) # if cached_zoom is not None: # resp_dict['zoom_to']=cached_zoom # else: g = GeoIP2() try: if g.country(ip)['country_code'] == settings.COUNTRY_CODE: resp_dict['zoom_to'] = list(g.lat_lon(ip)) else: resp_dict['zoom_to'] = settings.DEFAULT_ZOOM except AddressNotFoundError: resp_dict['zoom_to'] = settings.DEFAULT_ZOOM # cache.set('lat_lon_for::%s' % ip, resp_dict['zoom_to']) return render(request, self.template_name, resp_dict)
def create_tenant(domain='', **extra_fields): extra_fields.setdefault('name', '') extra_fields.setdefault('country', '') extra_fields.setdefault('currency', '') if domain and not freemail.is_free(domain): # We can guess some field values based on the domain. tld = tldextract.extract(domain) geo_ip = GeoIP2() if not extra_fields['name']: # Use the domain of the email address as tenant name. extra_fields['name'] = tld.domain.title() if not extra_fields['country']: try: country_code = geo_ip.country( tld.registered_domain).get('country_code') except (gaierror, AddressNotFoundError): pass else: if country_code in [c[0] for c in COUNTRIES]: extra_fields['country'] = country_code if extra_fields['country'] and not extra_fields['currency']: currency = get_territory_currencies( extra_fields['country'])[-1] if currency in [c[0] for c in CURRENCIES]: extra_fields['currency'] = currency if settings.BILLING_ENABLED: # Chargebee needs extra info on who to bill, so for now only create the plans without activating the trial. plan, created = Plan.objects.get_or_create( name=settings.CHARGEBEE_PRO_TRIAL_PLAN_NAME) billing = Billing.objects.create(plan=plan) else: billing = Billing.objects.create() tenant = Tenant.objects.create(billing=billing, **extra_fields) create_defaults_for_tenant(tenant) return tenant
def get_location_from_request(request): """ Returns location object. :param request: http request :type request: django.http.HttpRequest :return: location instance or empty dict :rtype: instance or dict """ from django.contrib.gis.geoip2 import GeoIP2 from geoip2.errors import AddressNotFoundError user_ip = get_ip_from_request(request=request) g = GeoIP2() try: location = g.city(user_ip) except AddressNotFoundError: return dict() else: return location
def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&units=metric&appid=a37ca4bee258beb72cf54b2b5cf190f3' city = "Las Vegas" city_weather = "" if request.method == 'POST': #only true if form is submited # form = CityForm(request.POST) # form.save() # will validate and save if validate print(request.POST.items()) city_weather = requests.get( url.format(request.POST["lat"], request.POST["lon"])).json() else: x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') ip = None if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') g = GeoIP2() try: print(ip) lat_lon = g.lat_lon(ip) city_weather = requests.get(url.format(lat_lon[0], lat_lon[1])).json() except: url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=a37ca4bee258beb72cf54b2b5cf190f3' city_weather = requests.get(url.format(city)).json() weather_data = [] weather = { 'city': city_weather['name'], 'temperature': city_weather['main']['temp'], 'description': city_weather['weather'][0]['description'], 'lat': city_weather['coord']['lat'], 'lon': city_weather['coord']['lon'], 'icon': city_weather['weather'][0]['icon'], } context = weather return render(request, 'weatherapp/index.html', context) #returns the index.html template
def get_form_kwargs(self): # Pass 'self.request' object to PostForm instance kwargs = super(MemberLoginView, self).get_form_kwargs() kwargs['recaptcha'] = False if member_settings.GOOGLE_RECAPTCHA_SESSION_KEY in self.request.session: kwargs['recaptcha'] = True try: ip_address = get_client_ip(self.request)[0] if ip_address not in ['127.0.0.1']: country = GeoIP2().country(ip_address) if country['country_code'] and country['country_code'].upper() not in settings.WHITE_COUNTRY_CODES: kwargs['recaptcha'] = True except AddressNotFoundError: pass return kwargs
def test04_city(self, gethostbyname): "GeoIP city querying methods." gethostbyname.return_value = "129.237.192.1" g = GeoIP2(country="<foo>") for query in (self.fqdn, self.addr): # Country queries should still work. self.assertEqual( "US", g.country_code(query), "Failed for func country_code and query %s" % query, ) self.assertEqual( "United States", g.country_name(query), "Failed for func country_name and query %s" % query, ) self.assertEqual( {"country_code": "US", "country_name": "United States"}, g.country(query), ) # City information dictionary. d = g.city(query) self.assertEqual("NA", d["continent_code"]) self.assertEqual("North America", d["continent_name"]) self.assertEqual("US", d["country_code"]) self.assertEqual("Lawrence", d["city"]) self.assertEqual("KS", d["region"]) self.assertEqual("America/Chicago", d["time_zone"]) self.assertFalse(d["is_in_european_union"]) geom = g.geos(query) self.assertIsInstance(geom, GEOSGeometry) for e1, e2 in ( geom.tuple, g.coords(query), g.lon_lat(query), g.lat_lon(query), ): self.assertIsInstance(e1, float) self.assertIsInstance(e2, float)
def payment_pingback(request): ip = get_ip(request) g = GeoIP2() try: country = g.country(ip) if country["country_name"] == "Georgia": user_language = 'ka_GE' translation.activate(user_language) response = HttpResponse() response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language) elif country["country_name"] == "Russia" or country[ "country_name"] == "Ukraine" or country[ "country_name"] == "Belarus" or country[ "country_name"] == "Latvia" or country[ "country_name"] == "Lithuania" or country[ "country_name"] == "Moldova" or country[ "country_name"] == "Estonia": user_language = 'ru' translation.activate(user_language) response = HttpResponse() response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language) except: pass test = request.GET.dict() test2 = request.GET.get('uid') pingback = Pingback(test, request.META['REMOTE_ADDR']) if pingback.validate(): virtual_currency = pingback.get_vc_amount() if pingback.is_deliverable(): # deliver the virtual currency print('OK') elif pingback.is_cancelable(): # withdraw the virtual currency pass print( 'Fail' ) # Paymentwall expects response to be OK, otherwise the pingback will be resent else: print(pingback.get_error_summary()) return render(request, 'payment/pingback.html')
def process_request(self, request): """ Add country info _before_ view is called. The country info is stored in the session between requests, so we don't have to do the lookup on each request, unless the client IP has changed. """ try: self.geoip2 = GeoIP2() except GeoIP2Exception: return None ip_address = self.remote_addr(request) data = request.session.get(GeoIP2Middleware.SESSION_KEY) if data is None: data = self.get_geo_data(ip_address).to_dict() elif data['ip_address'] != ip_address: data = self.get_geo_data(ip_address).to_dict() request.session[GeoIP2Middleware.SESSION_KEY] = request.geo_data = data
def test03_country(self, gethostbyname): "GeoIP country querying methods." gethostbyname.return_value = '128.249.1.1' g = GeoIP2(city='<foo>') for query in (self.fqdn, self.addr): self.assertEqual( 'US', g.country_code(query), 'Failed for func country_code and query %s' % query ) self.assertEqual( 'United States', g.country_name(query), 'Failed for func country_name and query %s' % query ) self.assertEqual( {'country_code': 'US', 'country_name': 'United States'}, g.country(query) )
def process_request(self, request): g = GeoIP2() abbrs = [i['abbreviation'] for i in CountryFlag.objects.all().values('abbreviation')] _row = 'ROW' if get_client_ip(request) != '127.0.0.1': try: country = g.country(get_client_ip(request))\ .get('country_code') if country in abbrs: request.country = country else: request.country = _row except AddressNotFoundError: request.country = _row else: request.country = _row if 'country' in request.session and request.session['country']: request.country = request.session['country'] return None
def test03_country(self, gethostbyname): "GeoIP country querying methods." gethostbyname.return_value = "128.249.1.1" g = GeoIP2(city="<foo>") for query in (self.fqdn, self.addr): self.assertEqual( "US", g.country_code(query), "Failed for func country_code and query %s" % query, ) self.assertEqual( "United States", g.country_name(query), "Failed for func country_name and query %s" % query, ) self.assertEqual( {"country_code": "US", "country_name": "United States"}, g.country(query), )
def get(self, request): resp_dict = { 'login_error': request.GET.get('login_error', 0), 'page': 'single', 'org_types': OrganizationType.objects.all(), 'test_alarm': False } claim_type_sets = {} for org_type in resp_dict['org_types']: claim_type_set = [] for claim_type in org_type.claimtype_set.all(): claim_type_set.append({ 'id': claim_type.id, 'value': claim_type.name }) claim_type_sets[org_type.type_id] = claim_type_set resp_dict['claim_types'] = mark_safe(json.dumps(claim_type_sets)) if settings.RECAPTCHA_ENABLED is False: settings.RECAPTCHA_PUBLIC = '' resp_dict['recaptcha_public'] = settings.RECAPTCHA_PUBLIC if settings.TEST_SERVER: resp_dict['test_alarm'] = True if hasattr(settings, 'TEST_COORDINATES'): resp_dict['zoom_to'] = getattr(settings, 'TEST_COORDINATES') else: g = GeoIP2() ip = get_client_ip(request) try: if g.country(ip)['country_code'] == settings.COUNTRY_CODE: resp_dict['zoom_to'] = list(g.lat_lon(ip)) else: resp_dict['zoom_to'] = settings.DEFAULT_ZOOM except AddressNotFoundError: resp_dict['zoom_to'] = settings.DEFAULT_ZOOM return render(request, self.template_name, resp_dict)
def serve(self, request): default = super(RegionRedirectionPage, self).serve(request) # Check if user came here from a different page if 'QUERY_STRING' in request.META and 'selector=true' in request.META[ 'QUERY_STRING']: # Then they came from a page looking to go to a different page. # Which also means we can assume they don't want to be prompted # to change language or region. This will get used by the includes # prompt (language_location_prompt.html), so we set a cookie to # make sure they don't get prompted again request.session['chosen_region_or_language'] = True # We also want to make sure that we store the correct site_region cookie # on the home page, so we redirect them to the correct region home page, # See how we handle that in get_context. return default elif request.session.get('site_region'): # We know that they have been to the home page once before, and # they're not looking to change region/language otherwise the above # case would have caught them. return HttpResponseRedirect(self.url + request.session.get('site_region') + '/') # Check Users IP client_ip, is_routable = get_client_ip(request) if client_ip: if is_routable: geo = GeoIP2() detected_region = geo.country(client_ip)['country_code'] if not HomePage.objects.filter(region=detected_region.lower()): # Detected region does not have a home page, so bring them to self for them to pick return default # This means that the region detected is an available HomePage, direct user there, automatically. return HttpResponseRedirect(self.url + detected_region.lower() + '/') return default
def get_login_logs(user, count): cache_key = 'member.member_tags.get_login_logs({})'.format(user.id) cache_time = settings.CACHES['default']['TIMEOUT'] logs = cache.get(cache_key) if not logs: logs = LoginLog.objects.filter(user=user).order_by('-created')[:count] for log in logs: log.country_code = None try: if log.ip_address not in ['127.0.0.1']: country = GeoIP2().country(log.ip_address) log.country_code = country['country_code'].lower() except AddressNotFoundError: pass cache.set(cache_key, logs, cache_time) return logs
def home(request): g = GeoIP2() x = g.country('google.com') x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') #if x_forwarded_for: #ip = request.META.get('REMOTE_ADDR') user = request.user ip = request.META.get('HTTP_X_FORWARDED_FOR') y = g.city('183.82.219.109') lat, long = g.lat_lon('183.82.219.109') context = { 'x': x, 'y': y, 'ip': ip, 'lat': lat, 'long': long, 'user': user } return render(request, 'home.html', context)
def link_redirect_view(request, link_id): link = get_object_or_404(Link, pk=link_id) g = GeoIP2() ip = request.META.get('REMOTE_ADDR', None) if ip == '127.0.0.1': my_country_code = 'RS' else: my_country_code = g.country(ip)['country_code'] # print("get ip ", request.META.get('HTTP_X_FORWARDED_FOR')) redirect_page = "https://google.com" linkprefs = link.linkpref_set.all() rps = {} for lp in linkprefs: print(lp.country.code) if lp.country.code == my_country_code: rps[lp.landing_page] = lp.weight redirect_page = np.random.choice(list(rps.keys()), p=list(rps.values())) print(redirect_page) return redirect(redirect_page)
def get_geo_from_ip(ip) -> tuple: """Get geometrical info from an IP address based on GeoLite2 databases. :param ip: user IP address :type ip: str :return: geometrical data """ ######################### # Practically just for testing purposes, because GeoLite2 doesn't contain 127.0.0.1 IP address # TODO: remove when done testing if ip == '127.0.0.1': ip = '89.74.26.21' # Katowice ######################### g = GeoIP2() country = g.country(ip) city = g.city(ip) lat, lon = g.lat_lon(ip) return country, city, lat, lon
def get_city_from_request(request): if GeoIP2 is None: return ip = get_client_ip(request) if not ip: logger.warning('No IP found on request: %s', request) return try: g = GeoIP2() except Exception as e: logger.exception(e) return try: result = g.city(ip) except Exception as e: logger.exception(e) return if result and result.get('latitude'): return result
def assignment_upload(request): if request.method == 'POST' and request.user.is_authenticated: active_support = User.objects.filter( Q(is_superuser=True) & Q(is_active=True)).first() form = AssignmentDocumentForm(request.POST, request.FILES) if form.is_valid(): ip = get_ip(request) geographical_location = GeoIP2() data = geographical_location.city(ip) country = data["country_name"] form.instance.ip_address = ip form.instance.location = country form.instance.creator = request.user form.instance.support = active_support form.save() messages.success( request, 'Assignment has been successfully uploaded.Thank you') return redirect('assignments:assignment_list') else: form = AssignmentDocumentForm() return render(request, 'upload.html', {'form': form})