Skip to main content

This module gives you a DateField same as Django’s DateField but you can get and query data based on Jalali Date

Status

https://github.com/slashmili/django-jalali/workflows/Tests/badge.svg?branch=main https://img.shields.io/pypi/v/django_jalali.svg https://img.shields.io/pypi/pyversions/django-jalali.svg https://img.shields.io/pypi/djversions/django-jalali.svg

Dependencies

Supported Databases

  • SQLite

  • PostgreSQL

Install

pip install django_jalali

To use DRF serializer field:

pip install django_jalali[drf]

Usage

  1. Run :

$ django-admin startproject jalali_test
  1. Start your app :

$ python manage.py startapp foo
  1. Edit your Django project’s settings.py file to include django_jalali and your application in the INSTALLED_APPS list. Make sure that django_jalali is listed before your apps for proper functionality.

    Additionally, you can configure library settings using the JALALI_SETTINGS dictionary. If a setting is not explicitly defined, the default values will be used.

    # settings.py
    INSTALLED_APPS = [
        "django.contrib.admin",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.sessions",
        "django.contrib.messages",
        "django.contrib.staticfiles",
        "django_jalali",  # Place this before your custom apps
    ]
    
    JALALI_SETTINGS = {
        # JavaScript static files for the admin Jalali date widget
        "ADMIN_JS_STATIC_FILES": [
            "admin/jquery.ui.datepicker.jalali/scripts/jquery-1.10.2.min.js",
            "admin/jquery.ui.datepicker.jalali/scripts/jquery.ui.core.js",
            "admin/jquery.ui.datepicker.jalali/scripts/jquery.ui.datepicker-cc.js",
            "admin/jquery.ui.datepicker.jalali/scripts/calendar.js",
            "admin/jquery.ui.datepicker.jalali/scripts/jquery.ui.datepicker-cc-fa.js",
            "admin/main.js",
        ],
        # CSS static files for the admin Jalali date widget
        "ADMIN_CSS_STATIC_FILES": {
            "all": [
                "admin/jquery.ui.datepicker.jalali/themes/base/jquery-ui.min.css",
                "admin/css/main.css",
            ]
        },
    }
  2. Edit foo/models.py

from django.db import models
from django_jalali.db import models as jmodels


class Bar(models.Model):
    objects = jmodels.jManager()
    name = models.CharField(max_length=200)
    date = jmodels.jDateField()

    def __str__(self):
        return "%s, %s" % (self.name, self.date)


class BarTime(models.Model):
    objects = jmodels.jManager()
    name = models.CharField(max_length=200)
    datetime = jmodels.jDateTimeField()

    def __str__(self):
        return "%s, %s" % (self.name, self.datetime)
  1. Run

$ python manage.py makemigrations
Migrations for 'foo':
  foo/migrations/0001_initial.py:
     - Create model Bar
     - Create model BarTime
$ python manage.py migrate
Running migrations:
    Applying foo.0001_initial... OK
  1. Test it

$ python manage.py shell
Python 3.8.18 (default, Nov 26 2018, 15:26:54)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from foo.models import Bar
>>> import jdatetime
>>> today = jdatetime.date(1390, 5, 12)
>>> mybar = Bar(name="foo", date=today)
>>> mybar.save()
>>> mybar.date
jdatetime.date(1390, 5, 12)
>>> Bar.objects.filter(date=today)
[<Bar: foo, 1390-05-12>]
>>> Bar.objects.filter(date__gte="1390-5-12")
[<Bar: foo, 1390-05-12>]
>>> Bar.objects.filter(date='1363-8-01')
[]
>>> from foo.models import BarTime
>>> BarTime(name="Bar Time now", datetime=jdatetime.datetime(1380,8,2,12,12,12)).save()
>>> BarTime.objects.filter(datetime__date=jdatetime.datetime(1380,8,2,12,12,12))
[<BarTime: Bar Time now, 1380-08-0212:12:12>]
>>> BarTime.objects.filter(datetime__date=jdatetime.date(1380,8,2))
[<BarTime: Bar Time now, 1380-08-0212:12:12>]
>>> BarTime.objects.filter(datetime__date="1380-08-02")
[<BarTime: Bar Time now, 1380-08-0212:12:12>]
>>> BarTime.objects.filter(datetime__lt=jdatetime.datetime(1380,8,2,12,12,12))
[]
>>> BarTime.objects.filter(datetime__lte=jdatetime.datetime(1380,8,2,12,12,12))
[<BarTime: Bar Time now, 1380-08-0212:12:12>]
>>> BarTime.objects.filter(datetime__gt='1380-08-02')
[<BarTime: Bar Time now, 1380-08-0212:12:12>]
>>> BarTime.objects.filter(datetime__gt=d)
[]
>>> BarTime.objects.filter(datetime__year=1380)
[<BarTime: Bar Time now, 1380-08-0212:12:12>]

⚠️ __month filter is not supported as explained in here

Using Templatetags

  1. You can use jformat filter to format your dates in templates:

{% load jformat %}
{{ my_date|jformat }} {# default formatting #}
{{ my_date|jformat:"%A %d %B %Y %H:%M" }} {# specific formatting #}

Admin Interface

  1. Create foo/admin.py

from foo.models import Bar, BarTime
from django.contrib import admin

from django_jalali.admin.filters import JDateFieldListFilter

# You need to import this for adding jalali calendar widget
import django_jalali.admin as jadmin


class BarAdmin(admin.ModelAdmin):
    list_filter = (
        ('date', JDateFieldListFilter),
    )


admin.site.register(Bar, BarAdmin)


class BarTimeAdmin(admin.ModelAdmin):
    list_filter = (
        ('datetime', JDateFieldListFilter),
    )


admin.site.register(BarTime, BarTimeAdmin)
  1. Config admin interface and fire up your django and enjoy using jalali date !

Django rest framework

There are serializer fields corresponding to jmodels.JDateField and jmodels.JDateTimeField for DRF:

from django_jalali.serializers.serializerfield import JDateField, JDateTimeField
from rest_framework.serializers import ModelSerializer

from foo.models import Bar, BarTime


class JDateFieldSerialializer(ModelSerializer):
    date = JDateField()

    class Meta:
        model = Bar
        exclude = []

class JDateTimeFieldSerializer(ModelSerializer):
    datetime = JDateTimeField()

    class Meta:
        model = BarTime
        exclude = []

Locale

In order to get the date string in farsi you need to set the locale to fa_IR

There are two ways to do achieve that, you can use of the approaches based on your needs

  • Run server with LC_ALL env:

$ LC_ALL=fa_IR python manage.py runserver
  • Set the locale in settings.py

LANGUAGE_CODE = 'fa-ir'
import locale
locale.setlocale(locale.LC_ALL, "fa_IR.UTF-8")
  • If using Docker, add the following to your Dockerfile:

FROM python:3.11-slim-bookworm

RUN apt-get update && apt-get -y install locales && \
 sed -i -e 's/# fa_IR UTF-8/fa_IR UTF-8/' /etc/locale.gen && \
 dpkg-reconfigure --frontend=noninteractive locales

Timezone Settings

From django_jalali version 3 and Django 2 you can use TIME_ZONE and USE_TZ settings to save datetime with project timezone

Development

You can contribute to this project forking it from GitHub and sending pull requests.

First fork the repository and then clone it:

$ git clone git@github.com:<you>/django-jalali.git

Initialize a virtual environment for development purposes:

$ python -m venv django_jalali_env
$ source ~/django_jalali_env/bin/activate

Then install the necessary requirements:

$ cd django-jalali
$ pip install -r requirements-test.txt

Unit tests are located in the tests folder and can be easily run with the pytest tool:

$ pytest

Before committing, you can run all the above tests against all supported Python and Django versions with tox. You need to install tox first:

$ pip install tox

And then you can run all tests:

$ tox

If you wish to limit the testing to specific environment(s), you can parametrize the tox run:

$ tox -e py39-django42

To add a new value to the Jalali settings, just add its default value to the DEFAULTS dictionary located in django_jalali/setting.py.

You can access the new setting in your code as shown below:

from django_jalali.settings import jalali_settings

custom_settings = jalali_settings.CUSTOM_SETTINGS

Javascrip Credits

This project includes few JS files to provide the functionality to show datepicker in Jalali in the admin area:

Metadata

Release files for django-jalali 7.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-jalali 7.4.0
File Size Uploaded Provenance
django_jalali-7.4.0.tar.gz 199.6 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for django-jalali 7.4.0
File Interpreter ABI Platform
django_jalali-7.4.0-py3-none-any.whl Python 3 none any Details

Total release size: 409.8 kB

Release files / django_jalali-7.4.0.tar.gz

Download URL django_jalali-7.4.0.tar.gz
Size 199.6 kB
Tags Source
SHA-256 checksum
How to use checksums
c1beb70625e5f34f79df488f25073e45049194a0d4193e0e0348369a425c4fb0
BLAKE2b-256 checksum
How to use checksums
19fcc1f1c1eefdd4e258c817e272d29da398e83ec6b976fbb4dc1f00b18455c8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.9

Release files / django_jalali-7.4.0-py3-none-any.whl

Download URL django_jalali-7.4.0-py3-none-any.whl
Size 210.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b7472b5bb54a3545607f6c5e03f2778bd555f79015a77e06670a3d9d4045e7e1
BLAKE2b-256 checksum
How to use checksums
3392bfe5bf23e0593abe550b4af6d9ba51e083dd07b5ece8bd4be5cf4e7739c7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.9

Security for django-jalali 7.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Release history Release notifications | RSS feed

This release

7.4.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page