GeoIP is functional

This commit is contained in:
2024-12-18 20:44:21 +09:00
parent de1059bca1
commit 091db21cf8
3 changed files with 27 additions and 3 deletions

View File

@@ -111,7 +111,7 @@ class ExternalDBSettingsAdmin(admin.ModelAdmin):
@admin.register(UserActivityLog)
class UserActivityLogAdmin(admin.ModelAdmin):
list_display = ("id", "ip", 'get_location',"formatted_timestamp", "date_time", "page_id", "url_parameters", "page_url" ,"created", "page_title", "type", "hits")
list_display = ("id", 'get_location',"formatted_timestamp", "date_time", "page_id", "url_parameters", "page_url" ,"created", "page_title", "type", "hits")
search_fields = ("page_title", "url_parameters")
list_filter = ("page_title", "created")
readonly_fields = ("created", "timestamp")

View File

@@ -2,6 +2,10 @@ from django.db import models
from hotels.models import Hotel
from hotels.models import Reservation
from datetime import datetime, timezone
from geoip2.errors import AddressNotFoundError
from geoip2.database import Reader
from django.conf import settings
import logging
class UserActivityLog(models.Model):
external_id = models.CharField(max_length=255, unique=True, verbose_name="Внешний ID", db_index=True)
@@ -61,10 +65,23 @@ class UserActivityLog(models.Model):
return "IP-адрес отсутствует"
try:
geoip_reader = Reader(settings.GEOIP_PATH + '/GeoLite2-City.mmdb')
db_path = f"{settings.GEOIP_PATH}/GeoLite2-City.mmdb"
geoip_reader = Reader(db_path)
response = geoip_reader.city(self.ip)
return f"{response.city.name}, {response.country.name}"
# Извлекаем город и страну на русском языке
city = response.city.names.get('ru', "Город неизвестен")
country = response.country.names.get('ru', "Страна неизвестна")
return f"{city}, {country}"
except AddressNotFoundError:
return "IP-адрес не найден в базе"
except FileNotFoundError:
logger.error(f"Файл базы данных GeoIP не найден по пути: {db_path}")
return "Файл базы данных GeoIP не найден"
except Exception as e:
logger.error(f"Ошибка при определении местоположения: {e}")
return "Местоположение недоступно"
class ExternalDBSettings(models.Model):
name = models.CharField(max_length=255, unique=True, help_text="Имя подключения для идентификации.")