Django-models Change format of dateField as "DD-MM-YYY" - python

I am using django-model's-dateField in my django-project and wanna change my dateFields format in admin view.
Currently (default) django gives format in YYYY-MM-DD but i want to modify that and in need of DD-MM-YYYY
I've been struggled too much in this and till no solution.
Also providing my code, may help..
my settings.py have:
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
models.py:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='User_Profile')
mobile = models.BigIntegerField()
alternative_number = models.BigIntegerField()
DOB = models.DateField()
and then i register it in admin
output on admin
as you can see in my admin page there is a dateField with format 2019-11-04 but i want in form of DD-MM-YYYY as 04-11-2019.
I tried LANGUAGE_CODE = 'de-at' that would work for me but the problem is, it changes the local language also.
refering a similer post:
Django - change default presentation format of model date field

You need just to override Django’s defaults locale settings. Add this to your settings.py file
from django.conf.locale.es import formats as es_formats
es_formats.DATETIME_FORMAT = "d M Y H:i:s"

fahim kazi was right: to define a models.DateField format, you need DATE_FORMAT, not DATETIME_FORMAT.
Yet Naveen Varshney was also right: not DATE_FORMAT nor DATETIME_FORMAT work without specifying the language, with es_formats for instance.
Therefore, from the combination of both answers, put the following in settings:
es_formats.DATE_FORMAT = 'd-m-y'
(Also '%d-%m-%y' printed %01-%08-%20 thus the % is not needed).
Thanks both.

add this to your settings.py
DATE_FORMAT = '%d-%m-%y'
for more check this date format

Related

Thousand separator not applied in Django admin

I registered my model in the Django Admin, but the Integer fields (they are read-only) show up without thousand separators; this happens in the admins list view and also in the admins model form.
I am using Django 1.11.9, with Python 3.6.
In my 'settings.py' I have the following:
USE_I18N = False
USE_L10N = False
DECIMAL_SEPARATOR = ','
THOUSAND_SEPARATOR = '.'
USE_THOUSAND_SEPARATOR = True
NUMBER_GROUPING = 3
Is there a way for the django-admin to apply thousand separators to my read-only fields?
-- EDIT --
This similar question (from sep 2015) does not have a simple answer that applies to all fields automaticly.
I did NOT get it working properly in the django-admin. Since I do not use the admin for user-facing sites, I'll let the numbers be formatted with commas instead of dots for now.
However, in other templates I resorted to using a custom template tag, based on the django documentation.
from django import template
from django.utils.encoding import force_text
register = template.Library()
#register.filter
def intdot(val_orig):
"""
Similar to 'django.contrib.humanize.intcomma', but with dots.
"""
val_text = force_text(val_orig)
try:
val_new = int(val_text)
except ValueError:
return ''
val_new = '{:,d}'.format(val_new)
val_new = val_new.replace(',', '.')
return val_new

datetime display and timezone converting in django

in settings.py file:
TIME_ZONE = 'UTC'
USE_TZ = True
in models.py:
from django.utils import timezone
date = models.DateTimeField(default = timezone.now())
before pip install pytz,date field in mysql db stored as UTC time, and date in front end webpage display as localtime. but after pip install pytz,date field in mysql db stored as UTC time, at the same time date in front end webpage display as UTC time too.
What is the reason for this?
How to do make sure that after pip install pytz,date field in mysql db stored as UTC time, and date in front end webpage display as localtime?
BTW, which library is more easily done than pytz?
Just change your TIME_ZONE setting to your local time's pytz.
e.g.
TIME_ZONE = 'Asia/Dubai'

Django: Store gmt time in database table instead of local time

In my customer model I have two datetime fields for storing created and updated time.
datetime_created = models.DateTimeField(auto_now_add=True)
datetime_updated = models.DateTimeField(auto_now=True)
When I create a customer, Now it is storing the local time in the database, When I get this customer data through API, It is returning the datetime in gmt time. This is fine. But I want to save the gmt time in the database. I think storing local time in database is not a good practice.
Date settings in settings.py file is
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
I have already installed "pip install pytz" module and my database is postgresql.
Best practice is to save it in UTC format.
USE_TZ = True in your settings, Django stores date and time information in UTC in the database otherwise it will store naive date time
You're rigth, the best practice is to save in UTC your datetime fields, and to convert it to your convenience in your views using pytz or in your templates using tz tag.
IE, you can use pytz to convert your datetime in an specific datetime in your views
import pytz
datetime_with_new_tz = object.created_at.astimezone(pytz.timezone(YOUR_LOCAL_TIMEZONE))`
if you want to convert the timezone in your template, you can use tz
{% load tz %}
{{object.created_at|timezone:YOUR_LOCAL_TIMEZONE}}

Django - query (month/day) filter only works when USE_TZ = False

How can I get the "latest_events_list" query below to work with day/month?
The below query only works if USE_TZ = False in settings.py. When I set USE_TZ = True, it doesn't query any objects.
Query for "year" works regardless of USE_TZ settings.
begin_datetime is a DateTime field in Event model.
views.py
today = datetime.datetime.now()
# list of events ordered and filter
latest_events_list = Event.objects.filter(begin_datetime__day = today.day)
My guess has to do with UTC and localtime - but I'm not sure. Thanks!
As Gocht helped mention in his comment above:
My MySQL server timezone needed to be in UTC time zone.
In addition, for those looking to change server time zone - be sure to restart the server or else changes may not take place.
Cheers

Django DateTimeField from form to UTC

I have a small Django app with a form, wich saves some data to the DB.
Here's the form:
class SomeForm(forms.Form):
time = forms.DateTimeField()
...
And the view, where I save it:
class AccountAddIncome(View):
def save(self, form):
model = Model(
time=form.cleaned_data['time']
)
model.save()
def post(self, request, *args, **kwargs):
form = SomeForm(request.POST)
if form.is_valid():
self.save(form)
return redirect(self.success_url)
else:
...
My problem is, that the Django admin says: "Note: You are 1 hour ahead of server time."
The date command on my Ubuntu (the server) says exactly the same date as my computer has.
But, when I save this object in the DB, and make the following query:
Model.objects.filter(time__lt=timezone.now())
django do not list the previously saved model for an hour. If I go to the admin, and set the time back one hour, django'll show that object.
So, my question is, what's the best practice, to manage datetime objects in django?
I want to save everything in UTC, but I cannot convert that datetime from the form to UTC.
go to settings.py of your Django project
comment timezone settings and use TIME_ZONE = timezone.now()
from django.utils import timezone
TIME_ZONE = timezone.now()
# TIME_ZONE = 'UTC'
# USE_I18N = True
# USE_L10N = True
# USE_TZ = True
Than you will never see this - Note: You are 1 hour ahead of server time.

Categories