slashmili / django-jalali

Jalali DateField support for Django model
http://pypi.python.org/pypi/django_jalali
BSD 3-Clause "New" or "Revised" License
240 stars 50 forks source link

Displays Gregorian date #249

Open omidshojaee opened 3 weeks ago

omidshojaee commented 3 weeks ago

Configurations

Here's my setup:

models.py:

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

class Post(models.Model):
    publish = jmodels.jDateTimeField(default=timezone.now)

With the above setup, the add form in the admin site still displays the Gregorian date:

image

And the datepicker is showing the wrong date (it shows Shahrivar because now it is month 6 of Gregorian calendar):

image

Ironically, in the same project, in my custom user model I have this:

models.py

date_joined = jmodels.jDateTimeField(default=timezone.now)

And this is how it looks in the Admin site:

image

So it works without any issue.

The only difference between those two models is that one of them is my own, and the other one is a subclass of Django's User model.

omidshojaee commented 2 weeks ago

I figured out what is the issue.

If I define the field like this:

publish = jmodels.jDateTimeField()

Then this is what I have in the admin site (i.e the datepicker works correctly)

image

However if I change the field to this:

publish = jmodels.jDateTimeField(default=timezone.now)

Then the datepicker does not work:

image

So, is that intentional? What is the solution here?

hramezani commented 2 weeks ago

have you tested jmodels.jDateTimeField(auto_now_add=True)?

omidshojaee commented 2 weeks ago

Yes it works however the field disappears from the admin site because auto_now_add means set the field value only once during object creation and it is not meant to be edited later.

I need to set the field's value automatically, but edit it later if I need to. That's why timezone.now is the suitable option.

slashmili commented 2 weeks ago

What if you use

    publish = jmodels.jDateTimeField(default=jdatetime.datetime.now)

if you want to get the timezone based on the setting,s you need to write a function like

def current_datetime():
  dt = jdatetime.datetime.now()
  new_dt = .. do something with dt to get the timezone from settings and apply it on the datetime
  new_dt

class Post(models.Model):
    publish = jmodels.jDateTimeField(default=current_datetime)

if you figure out how is it done, a PR is welcomed to add it as django_jalali.utils.timzeone

omidshojaee commented 2 weeks ago

how about

from django.utils import timezone
publish = jmodels.jDateTimeField(default=jdatetime.datetime.now(tz=timezone.get_current_timezone()))
slashmili commented 1 week ago

Looks good!