refactor: global project refinement, DRY consolidation, and documentation overhaul

This commit represents a comprehensive improvement of the library's architecture, developer experience, and documentation accuracy.

Core Refactoring:
- apply DRY principle to models.py by introducing BaseNepaliBSField and BaseLocationField
- standardize widget logic in widgets.py using NepaliWidgetMixin
- centralize admin filtering logic into BaseNepaliDateFilter

New Features & API:
- add NepaliMonthFilter for Django Admin and NepaliDateMonthFilter for DRF
- implementation of HTMX-driven location chaining for dynamic address selects
- extend demo project with comprehensive DRF search, ordering, and filter examples

Configuration & Sync:
- implement global NEPKIT settings in conf.py (DEFAULT_LANGUAGE, ADMIN_DATEPICKER, etc.)
- universalize BS_DATE_FORMAT/BS_DATETIME_FORMAT across the entire stack
- synchronize frontend datepicker initialization with backend date formats

Documentation & DX:
- complete rewrite of README.md into high-energy, factual, English-only guides
- project-wide audit and simplification of comments/docstrings for beginner accessibility
- expanded 'Technical Design' and 'FAQ' sections covering data integrity and storage
- added docs/migration_guide.py for bulk AD-to-BS data transitions

Quality & Maintenance:
- fixed all E402 module-level import errors across the library
- verified codebase with project-wide ruff checks (all checks passed)
This commit is contained in:
sankalp committed 2026-01-30 17:00:33 +05:45
1 parent 09f302ceaa
commit 1338f9e5fe
32 files changed
+3002 -531

No files matched your search

+87 -56
View File
@@ -2,16 +2,17 @@ from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from nepali.datetime import nepalidate, nepalidatetime
from django_nepkit.conf import nepkit_settings
from django_nepkit.models import NepaliDateField, NepaliDateTimeField
from django_nepkit.utils import (
try_parse_nepali_date,
try_parse_nepali_datetime,
)
from django_nepkit.conf import nepkit_settings
from django_nepkit.utils import BS_DATE_FORMAT
def _format_nepali_common(value, try_parse_func, format_string, ne, cls_type):
"""Internal helper for formatting Nepali objects."""
"""Helper to format dates/times with optional Devanagari support."""
if value is None:
return ""
@@ -40,9 +41,7 @@ def format_nepali_date(date_value, format_string="%B %d, %Y", ne=False):
)
def format_nepali_datetime(
datetime_value, format_string=None, ne=False
):
def format_nepali_datetime(datetime_value, format_string=None, ne=False):
"""
Format a nepalidatetime object with Nepali month names.
"""
@@ -57,15 +56,12 @@ def format_nepali_datetime(
)
class NepaliDateFilter(admin.FieldListFilter):
"""
A list filter for NepaliDateField to filter by BS Year.
"""
class BaseNepaliDateFilter(admin.FieldListFilter):
"""Base class for date filters (Year/Month)."""
def __init__(self, field, request, params, model, model_admin, field_path):
self.parameter_name = f"{field_path}_bs_year"
self.parameter_name = f"{field_path}_{self.suffix}"
super().__init__(field, request, params, model, model_admin, field_path)
self.title = _("Nepali Date (Year)")
def expected_parameters(self):
return [self.parameter_name]
@@ -76,40 +72,85 @@ class NepaliDateFilter(admin.FieldListFilter):
"query_string": changelist.get_query_string(remove=[self.parameter_name]),
"display": _("All"),
}
current_year = nepalidate.today().year
for year in range(current_year - 10, current_year + 2):
for value, display in self.get_filter_options():
yield {
"selected": self.used_parameters.get(self.parameter_name) == str(year),
"selected": self.used_parameters.get(self.parameter_name) == str(value),
"query_string": changelist.get_query_string(
{self.parameter_name: str(year)}
{self.parameter_name: str(value)}
),
"display": str(year),
"display": display,
}
def queryset(self, request, queryset):
value = self.used_parameters.get(self.parameter_name)
if value:
year = int(value)
# Convert BS year range to AD date range
start_date_bs = nepalidate(year, 1, 1)
# Find last day of the year. Some BS years end on the 30th,
# so we try 31 first and then fall back to 30 if that date
# is not valid.
try:
end_date_bs = nepalidate(year, 12, 31)
except ValueError:
end_date_bs = nepalidate(year, 12, 30)
start_date_ad = start_date_bs.to_date()
end_date_ad = end_date_bs.to_date()
return queryset.filter(
**{f"{self.field_path}__range": (start_date_ad, end_date_ad)}
)
return self.apply_filter(queryset, value)
return queryset
def get_filter_options(self):
raise NotImplementedError
# Register NepaliDateFilter as the default list filter for NepaliDateField
def apply_filter(self, queryset, value):
raise NotImplementedError
class NepaliDateFilter(BaseNepaliDateFilter):
"""Filter by Nepali Year (e.g., 2080)."""
suffix = "bs_year"
title = _("Nepali Date (Year)")
def get_filter_options(self):
current_year = nepalidate.today().year
return [(y, str(y)) for y in range(current_year - 10, current_year + 2)]
def apply_filter(self, queryset, value):
if BS_DATE_FORMAT.startswith("%Y"):
separator = BS_DATE_FORMAT[2] if len(BS_DATE_FORMAT) > 2 else "-"
return queryset.filter(
**{f"{self.field_path}__startswith": f"{value}{separator}"}
)
return queryset.filter(**{f"{self.field_path}__icontains": f"{value}"})
class NepaliMonthFilter(BaseNepaliDateFilter):
"""Filter by Nepali Month (e.g., Baisakh)."""
suffix = "bs_month"
title = _("Nepali Date (Month)")
def get_filter_options(self):
ne = nepkit_settings.DEFAULT_LANGUAGE == "ne"
names = [
("बैशाख", "Baisakh"),
("जेठ", "Jestha"),
("असार", "Ashad"),
("साउन", "Shrawan"),
("भदौ", "Bhadra"),
("असोज", "Ashwin"),
("कात्तिक", "Kartik"),
("मंसिर", "Mangsir"),
("पुष", "Poush"),
("माघ", "Magh"),
("फागुन", "Falgun"),
("चैत", "Chaitra"),
]
return [(f"{i:02d}", n[0] if ne else n[1]) for i, n in enumerate(names, 1)]
def apply_filter(self, queryset, value):
from django_nepkit.utils import BS_DATE_FORMAT
if BS_DATE_FORMAT == "%Y-%m-%d":
return queryset.filter(**{f"{self.field_path}__contains": f"-{value}-"})
separator = BS_DATE_FORMAT[2] if len(BS_DATE_FORMAT) > 2 else "-"
return queryset.filter(
**{f"{self.field_path}__contains": f"{separator}{value}{separator}"}
)
# Standard filter for any NepaliDateField in Admin
admin.FieldListFilter.register(
lambda f: isinstance(f, NepaliDateField),
NepaliDateFilter,
@@ -118,10 +159,7 @@ admin.FieldListFilter.register(
class NepaliAdminMixin:
"""
Mixin for Django admin classes that provides Nepali date utilities.
Makes format_nepali_date and NepaliDateFilter available without explicit imports.
"""
"""Provides date formatting tools for Admin classes."""
def _get_field_ne_setting(self, field_name):
"""
@@ -158,7 +196,6 @@ class NepaliAdminMixin:
ne: If True, format using Devanagari script. If None, auto-detect from field or global settings (default: None)
field_name: Name of the field to auto-detect 'ne' setting from (optional)
"""
# Auto-detect 'ne' from field if not explicitly provided
if ne is None and field_name:
ne = self._get_field_ne_setting(field_name)
elif ne is None:
@@ -182,7 +219,6 @@ class NepaliAdminMixin:
ne: If True, format using Devanagari script. If None, auto-detect from field or global settings (default: None)
field_name: Name of the field to auto-detect 'ne' setting from (optional)
"""
# Auto-detect 'ne' from field if not explicitly provided
if ne is None and field_name:
ne = self._get_field_ne_setting(field_name)
elif ne is None:
@@ -193,9 +229,7 @@ class NepaliAdminMixin:
class NepaliModelAdmin(NepaliAdminMixin, admin.ModelAdmin):
"""
Base ModelAdmin class with Nepali date utilities built-in.
NepaliDateField and NepaliDateTimeField in list_display are automatically
formatted (using the field's ne setting). No manual display methods needed.
Standard Admin class that automatically formats Nepali dates in lists.
Example:
from django_nepkit import NepaliModelAdmin, NepaliDateFilter
@@ -206,11 +240,12 @@ class NepaliModelAdmin(NepaliAdminMixin, admin.ModelAdmin):
list_filter = (("birth_date", NepaliDateFilter),)
"""
# Make NepaliDateFilter available as a class attribute
# Make filters available as class attributes
NepaliDateFilter = NepaliDateFilter
NepaliMonthFilter = NepaliMonthFilter
def _make_nepali_display(self, field_name, formatter_method):
"""Generic helper to return a callable that formats a Nepali field for list_display."""
"""Helper to create display columns for Nepali dates."""
admin_instance = self
try:
field = self.model._meta.get_field(field_name)
@@ -257,19 +292,18 @@ class NepaliModelAdmin(NepaliAdminMixin, admin.ModelAdmin):
result.append(item)
return result
# Ensure admin forms render Nepali fields with the proper widget,
# even if a project doesn't provide custom ModelForms.
def formfield_for_dbfield(self, db_field, request, **kwargs):
"""
Force Nepali widgets in Django admin without requiring user forms.
"""
"""Automatically use NepaliDatePicker in the admin form."""
try:
from django_nepkit.models import NepaliDateField, NepaliDateTimeField
from django_nepkit.widgets import NepaliDatePickerWidget
except Exception:
return super().formfield_for_dbfield(db_field, request, **kwargs)
if isinstance(db_field, (NepaliDateField, NepaliDateTimeField)) and nepkit_settings.ADMIN_DATEPICKER:
if (
isinstance(db_field, (NepaliDateField, NepaliDateTimeField))
and nepkit_settings.ADMIN_DATEPICKER
):
# Pass ne/en parameters from field to widget if they exist
widget_kwargs = {}
if hasattr(db_field, "ne"):
@@ -281,10 +315,7 @@ class NepaliModelAdmin(NepaliAdminMixin, admin.ModelAdmin):
return super().formfield_for_dbfield(db_field, request, **kwargs)
class Media:
"""
Django admin ships jQuery as `django.jQuery` (not `window.jQuery`).
The Nepali date picker library expects a global `jQuery`, so we bridge it.
"""
"""Loads the Nepali Datepicker and bridging scripts."""
css = {
"all": (
@@ -302,9 +333,9 @@ class NepaliModelAdmin(NepaliAdminMixin, admin.ModelAdmin):
)
# Exporting for easy usage
__all__ = [
"NepaliDateFilter",
"NepaliMonthFilter",
"format_nepali_date",
"format_nepali_datetime",
"NepaliAdminMixin",