|
| 1 | +from django.utils import formats, timezone |
| 2 | +from rest_framework import serializers |
| 3 | +from swapper import load_model |
| 4 | + |
| 5 | +RadiusAccounting = load_model("openwisp_radius", "RadiusAccounting") |
| 6 | + |
| 7 | + |
| 8 | +class MonitoringRadiusAccountingSerializer(serializers.ModelSerializer): |
| 9 | + """ |
| 10 | + Read-only serializer for RADIUS accounting in monitoring integration |
| 11 | + that formats datetime fields server-side using Django's localization |
| 12 | + for consistency with Django admin datetime formatting. |
| 13 | + """ |
| 14 | + |
| 15 | + start_time = serializers.SerializerMethodField() |
| 16 | + stop_time = serializers.SerializerMethodField() |
| 17 | + |
| 18 | + def _format_datetime(self, dt): |
| 19 | + """ |
| 20 | + Format a datetime using Django's localization settings. |
| 21 | + Handles both naive and timezone-aware datetimes. |
| 22 | + """ |
| 23 | + if dt is None: |
| 24 | + return None |
| 25 | + if timezone.is_aware(dt): |
| 26 | + dt = timezone.localtime(dt) |
| 27 | + return formats.date_format(dt, "DATETIME_FORMAT") |
| 28 | + |
| 29 | + def get_start_time(self, obj): |
| 30 | + """Format start_time using Django's localization settings""" |
| 31 | + return self._format_datetime(obj.start_time) |
| 32 | + |
| 33 | + def get_stop_time(self, obj): |
| 34 | + """Format stop_time using Django's localization settings""" |
| 35 | + return self._format_datetime(obj.stop_time) |
| 36 | + |
| 37 | + class Meta: |
| 38 | + model = RadiusAccounting |
| 39 | + fields = [ |
| 40 | + "session_id", |
| 41 | + "unique_id", |
| 42 | + "username", |
| 43 | + "input_octets", |
| 44 | + "output_octets", |
| 45 | + "calling_station_id", |
| 46 | + "called_station_id", |
| 47 | + "start_time", |
| 48 | + "stop_time", |
| 49 | + ] |
| 50 | + read_only_fields = fields |
0 commit comments