Files
django-nepkit/django_nepkit/serializers.py
T
sankalp ed93467296 feat: revamp localization support with Devanagari (BS) integration and documentation
Implemented a comprehensive update to handle Nepali (Bikram Sambat) localization more robustly across models, forms, admin, and API serializers. This includes native support for Devanagari script output and a complete documentation overhaul.

Models & Fields:
- Added [NepaliFieldMixin](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/models.py:15:0-36:39) to support [ne](cci:1://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/admin.py:146:4-163:67) (Nepali) and [en](cci:1://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/widgets.py:4:0-10:16) (English) toggles for all custom fields.
- Updated [NepaliDateField](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/models.py:48:0-134:44), [NepaliDateTimeField](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/models.py:144:0-217:44), and [NepaliTimeField](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/models.py:137:0-141:34) with the new mixin and improved deconstruction.
- Enhanced address fields ([ProvinceField](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/models.py:220:0-262:23), [DistrictField](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/models.py:265:0-286:66), [MunicipalityField](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/models.py:289:0-310:66)) to support bilingual choices.

Admin Enhancements:
- Refactored date formatting into a common utility supporting Devanagari via `strftime_ne`.
- Updated [NepaliModelAdmin](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/admin.py:186:0-294:9) and [NepaliAdminMixin](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/admin.py:118:0-183:75) to auto-detect [ne](cci:1://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/admin.py:146:4-163:67) settings from model fields for [list_display](cci:1://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/admin.py:230:4-250:21).
- Improved widget injection in the admin to respect field-level localization settings.
- Added a JS bridge for admin jQuery compatibility with the Nepali datepicker.

Forms & Widgets:
- Introduced [NepaliWidgetMixin](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/widgets.py:13:0-38:12) to handle localization data attributes in the frontend.
- Updated [NepaliDatePickerWidget](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/widgets.py:63:0-99:42) with improved asset loading and Devanagari support.
- Fixed [NepaliDateFormField](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/forms.py:10:0-41:13) to correctly handle `empty_value` passed by the Django admin.

DRF (Serializers):
- Added [BaseNepaliBSField](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/serializers.py:21:0-106:48) to DRF serializers with support for `ne=True` for Devanagari output.
- Implemented specialized [NepaliDateSerializerField](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/serializers.py:114:0-122:28) and [NepaliDateTimeSerializerField](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/serializers.py:130:0-138:32).

Documentation:
- Completely revamped [README.md](cci:7://file:///home/sankalp/Projects/prod-django-nepkit/README.md:0:0-0:0) with professional design, badges, and detailed usage guides.
- Added explicit instructions for address chaining URLs and [NepaliAdminMixin](cci:2://file:///home/sankalp/Projects/prod-django-nepkit/django_nepkit/admin.py:118:0-183:75) usage.

Misc:
- Optimized address chaining JS logic.
- Updated example demo app models and migrations to reflect new field capabilities.
2026-01-30 13:32:33 +05:45

140 lines
4.1 KiB
Python

from __future__ import annotations
from typing import Any, Optional, Type
from nepali.datetime import nepalidate, nepalidatetime
try:
from rest_framework import serializers
except ModuleNotFoundError as e:
raise ModuleNotFoundError(
"django-nepkit DRF support is optional. Install with `django-nepkit[drf]` "
"to use `django_nepkit.serializers`."
) from e
from django_nepkit.utils import try_parse_nepali_date, try_parse_nepali_datetime
# --------------------------------------------------
# Base Serializer Field
# --------------------------------------------------
class BaseNepaliBSField(serializers.Field):
"""
Base DRF field for Nepali (BS) Date / DateTime.
- **Input**: BS string, or an already-parsed `nepalidate`/`nepalidatetime`
- **Output**: formatted BS string (configurable)
- **ne**: If True, output uses Devanagari script (default: False)
- **en**: If True, output uses English (default: True). When ne=True, en is False.
"""
format: str = ""
nepali_type: Type[object] = object
default_error_messages = {
"invalid": "Invalid Bikram Sambat value. Expected format: {format}.",
"invalid_type": "Invalid type. Expected a string.",
}
def __init__(
self,
*,
format: Optional[str] = None,
ne: bool = False,
en: bool = True,
**kwargs: Any,
) -> None:
"""
Args:
format: Optional `strftime` format used for representation.
If not provided, uses the class default.
ne: If True, output in Devanagari script (default: False).
en: If True, output in English (default: True). When ne=True, en is False.
"""
if format is not None:
self.format = format
self.ne = ne
if self.ne:
self.en = False
else:
self.en = en
super().__init__(**kwargs)
def _parse(self, value: str):
if self.nepali_type is nepalidate:
return try_parse_nepali_date(value)
if self.nepali_type is nepalidatetime:
return try_parse_nepali_datetime(value)
return None
def _format_value(self, value: Any) -> str:
"""Format value using strftime or strftime_ne (Devanagari) based on self.ne."""
if self.ne and hasattr(value, "strftime_ne"):
return value.strftime_ne(self.format) # type: ignore[attr-defined]
return value.strftime(self.format) # type: ignore[attr-defined]
def to_representation(self, value: Any) -> Optional[str]:
if value is None:
return None
if isinstance(value, self.nepali_type):
return self._format_value(value)
# If DB returns string, try to normalize it.
if isinstance(value, str):
parsed = self._parse(value)
if parsed is not None:
return self._format_value(parsed)
# Fallback: best-effort stringify (keeps behavior non-breaking)
return str(value)
def to_internal_value(self, data: Any):
if data in (None, ""):
return None
if isinstance(data, self.nepali_type):
return data
if not isinstance(data, str):
self.fail("invalid_type")
parsed = self._parse(data)
if parsed is not None:
return parsed
self.fail("invalid", format=self.format)
# --------------------------------------------------
# Nepali Date (BS)
# --------------------------------------------------
class NepaliDateSerializerField(BaseNepaliBSField):
"""
DRF field for Nepali BS Date (YYYY-MM-DD).
Pass ne=True for Devanagari output; default is English.
"""
format = "%Y-%m-%d"
nepali_type = nepalidate
# --------------------------------------------------
# Nepali DateTime (BS)
# --------------------------------------------------
class NepaliDateTimeSerializerField(BaseNepaliBSField):
"""
DRF field for Nepali BS DateTime (YYYY-MM-DD HH:MM:SS).
Pass ne=True for Devanagari output; default is English.
"""
format = "%Y-%m-%d %H:%M:%S"
nepali_type = nepalidatetime