28 lines
826 B
Python
28 lines
826 B
Python
# your_app/services.py
|
|
from django.contrib.gis.geoip2 import GeoIP2
|
|
from .models import VisitorLog
|
|
|
|
def log_visitor_location(ip_address):
|
|
# if ip_address in ['127.0.0.1', 'localhost']:
|
|
# return
|
|
if ip_address.startswith(('127.', '10.')):
|
|
|
|
print(f"DEBUG: Logged Skipped local IP {ip_address}")
|
|
return
|
|
|
|
try:
|
|
g = GeoIP2()
|
|
loc = g.city(ip_address)
|
|
VisitorLog.objects.create(
|
|
ip_address=ip_address,
|
|
country=loc.get('country_name'),
|
|
region=loc.get('region'),
|
|
city=loc.get('city')
|
|
)
|
|
except Exception:
|
|
# If the IP is not in the database (like your WiFi IP)
|
|
VisitorLog.objects.create(
|
|
ip_address=ip_address,
|
|
country="Anonymous/Private",
|
|
city="N/A"
|
|
) |