Django DateTimeWidget ValidationError with localization - python

I want to use django-datetime-widget in Polish language. But following instruction from project's github give me error. My situation is:
form:
class add_test_form(forms.Form):
test_date_finish = forms.DateTimeField(label="Termin zakonczenia testu", widget=DateTimeWidget(usel10n=True, bootstrap_version=3), localize=True)
view:
test = Test(test_date_start = request.POST['test_date_start'])
test.save()
model:
class Test(models.Model):
test_date_finish = models.DateTimeField()
settings.py:
LANGUAGE_CODE = 'pl-pl'
TIME_ZONE = 'Europe/Warsaw'
USE_I18N = True
USE_L10N = True
USE_TZ = True
I got ValidationError in Polish which translates into:
[...] value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[." "uuuuuu]][TZ] format.

Your date-time format isn't right, you should set it. This code in the project's docs may help you with that. Probably you should put this on your settings.py and change the format part according to your datetime format.
dateTimeOptions = {
'format': 'dd/mm/yyyy HH:ii P',
'autoclose': True,
'showMeridian' : True
}
widgets = {
#NOT Use localization and set a default format
'datetime': DateTimeWidget(options = dateTimeOptions)
}

Related

Django mock timezone aware datetime on creating model

I have a test where I create a few objects:
def test_get_courier_task_returns_couriers_tasks(self):
with patch('django.utils.timezone.now', return_value=make_aware(datetime(2018, 1, 24, 11, 57))):
task1 = TaskFactory()
response = json.loads(MyAPI.get_tasks_list(self.user.username))
print('[*] Response timestamp: {}'.format(response['content'][0]['timestamp']))
The Task has created_timestamp field with auto_add_now set to True and to_json() method which is used in get_tasks_list() above:
class Task(models.Model):
created_timestamp = models.DateTimeField(auto_now_add=True)
def to_json(self):
to_return = {
'timestamp': self.created_timestamp.strftime('%d-%m-%Y %H:%M')
}
return to_return
Unfortunately tests give this output:
[*] Response timestamp: 24-01-2018 10:57
I have checked that this is timezone aware, but instead of giving me UTC+1 it gives UTC+0 on saving. What do I have to do? I have USE_TZ = True in my settings and I have applied migrations. This question did not help with my problem.
It turned out that giving timezone explicityl helped:
with patch('django.utils.timezone.now', return_value=datetime(2018, 1, 24, 11, tzinfo=pytz.timezone('utc'))):
Try providing make_aware with the timezone you want.
Also checking for a specific time in the test is a bit circular, probably don't need to check for it and just make sure it runs and produces a timestamp.

TruncDate timezone parameter is not working in Django

Not able to change TImezone in Trunc functions. It always take timezone from settings.py
import pytz
ind = pytz.timezone('Asia/Calcutta')
Query:
queryset = Order.objects.annotate(date=TruncDate('created_at', tzinfo=ind)).values('date')
While inspecting sql query by queryset.query
SELECT DATE(CONVERT_TZ(`nm_order`.`created_at`, 'UTC', UTC)) AS `date` FROM `nm_order`
Reference: Trunc in Django
But for Extract, it's get working
ORM:
queryset = Order.objects.annotate(date=ExtractDay('created_at',tzinfo=ind)).values('date')
Query:
SELECT EXTRACT(DAY FROM CONVERT_TZ(`nm_order`.`created_at`, 'UTC', Asia/Calcutta)) AS `date` FROM `nm_order`
Am I miss something in Trunc ?
TimeZone Settings in my settings.py
IME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
You need to use TruncDay() instead of TruncDate. In the usage example just below that section of the documentation you'll see the difference between the two.
TruncDate does not take a timezone option - it uses the current timezone and gives you the date in that timezone.
I think the distinction between the two is that TruncDate returns a DateField which by definition cannot be timezone-aware. TruncDay on the other hand returns a DateTimeField(with time portion set to 00:00:00), which can be timezone aware.
From django 3.2, TruncDate now accepts tzinfo parameter. https://docs.djangoproject.com/en/dev/ref/models/database-functions/#django.db.models.functions.TruncDate
After Inspecting TruncDate Class looks like it doesn't have timezone option
class TruncDate(TruncBase):
kind = 'date'
lookup_name = 'date'
#cached_property
def output_field(self):
return DateField()
def as_sql(self, compiler, connection):
# Cast to date rather than truncate to date.
lhs, lhs_params = compiler.compile(self.lhs)
tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname)
lhs_params.extend(tz_params)
return sql, lhs_params

Django: DateTimeField taking UTC format only, not others

The time that is being inserted in database is default UTC, not the timezone based time..I do not understand why is this happening, even though I am particularly specifying, in the query, the time that I want to be inserted.
In my Model I have
class leave(models.Model):
date_created = models.DateTimeField(auto_now_add=True)
In my settings I have
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
In my views i am setting timezone based on employee country
if employees.objects.get(emp_id=request.user.username).emp_loc == 'IND':
tzone=pytz.timezone('Asia/Calcutta')
elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MLA':
tzone=pytz.timezone('Asia/Manila')
elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MPLS':
tzone=pytz.timezone('CST6CDT')
And then I am creating leave and updating timezone based on country
new_leave = leave.objects.create(employee=employees.objects.get(emp_id = userid.emp_id), start_date=sdt, end_date=edt, ltype=ltyp, message=des,date_created=datetime.now(tzone))
new_leave.save()
Thanks in Advance.
You can create a middleware that handles the conversion of date and time,
import pytz
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
class TimezoneMiddleware(MiddlewareMixin):
def process_request(self, request):
tzname = request.session.get('django_timezone')
if tzname:
timezone.activate(pytz.timezone(tzname))
else:
timezone.deactivate()
and then you can as easily create the view with the conditions that you indicated earlier.
Best if you read the documentation as Kevin suggested.

Django - localized date and time

I'm using Django 1.6 and I have to display a date. The timezone is Guayaquil (-05:00) and I have to get the date as:
{
'fecha': partido.fecha.strftime("%d %B"),
'hora': partido.fecha.strftime("%T"),
}
Expecting: '13 Junio' and '14:00:00' respectively, since that's the time saved and in Guayaquil timezone.
However what I get is the same time in UTC and months names in english: '13 June' and '19:00:00'.
What can I do to solve this issue?
You have to configure you time zone in your Django Settings
Choices can be found Here
Check in your settings.py:
TIME_ZONE = 'America/Guayaquil'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGE_CODE = 'es'

Django - ValueError: "strftime format ends with raw %" when DATE_INPUT_FORMATS and TIME_INPUT_FORMATS are set?

In Django I have form that is using the SplitDateTimeField which is set to have an initial value as shown below. When try view the template containing the form I get ValueError: "strftime format ends with raw %."
# forms.py
class DiscountForm(Form):
title = CharField(widget=TextInput(), required=True)
description = CharField(widget=Textarea(), required=True)
fineprint = CharField(widget=Textarea(), required=True)
start = SplitDateTimeField(
input_date_formats='%m/%d/%Y',
input_time_formats='%I:%M %p',
initial= lambda: dt.datetime.now(),
required=True
)
end = SplitDateTimeField(
input_date_formats='%m/%d/%Y',
input_time_formats='%I:%M %p',
initial= lambda: dt.datetime.now() + dt.timedelta(days=30),
required=True
)
limit = IntegerField(min_value=0, initial=0, required=True)
# relevant in settings.py
USE_I18N = False
USE_L10N = False
USE_TZ = True
DATETIME_INPUT_FORMATS = ('%m/%d/%Y %I:%M %p')
DATE_INPUT_FORMATS = ('%m/%d/%Y')
TIME_INPUT_FORMATS = ('%I:%M %p')
Here is my traceback: http://dpaste.org/y55eV/
Any guidance is greatly appreciated. Thank you
The arguments input_date_formats and input_time_formats need to be lists or tuples, not strings (see SplitDateTimeField in documentation). The error may be caused that it is now iterating over characters instead of multiple input formats.
Try changing the code to the following:
start = SplitDateTimeField(
input_date_formats=('%m/%d/%Y',),
input_time_formats=('%I:%M %p',),
initial= lambda: dt.datetime.now(),
required=True
)
end = SplitDateTimeField(
input_date_formats=('%m/%d/%Y',),
input_time_formats=('%I:%M %p',),
initial= lambda: dt.datetime.now() + dt.timedelta(days=30),
required=True
)

Categories

Resources