Django DateTimeField from form to UTC - python

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.

Related

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

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

Django Admin datetime in EST [duplicate]

This question already has answers here:
How to set a default TZ for django admin portal only?
(2 answers)
Closed 3 years ago.
In my application I need to show some datetimes in the admin section in EST timezone. I have the following configuration in settings.py:
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = False
Users chose differente timezones and works fine for them, ie; Thursday, May 16, 2019 12:00 AM EDT
But I want to show datetime in EST timezone in the admin section. Currently it will show all times in UTC as expected. I tried the following:
from datetime import datetime
from pytz import timezone
from django.contrib import admin
TZ = timezone('EST')
#admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
list_display = ('name', 'scheduled_date')
fieldsets = (
(None, {'fields': ('name', 'scheduled_date')}),
)
def scheduled_date(self, obj):
date = datetime(obj.scheduled_date, tzinfo=TZ)
return date
However the admin section is still showing time in UTC for scheduled_date
You can create a middleware that will change the timezone at runtime for every request coming from Admin.
For Instance:
import pytz
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
class AdminTimezoneMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.path.startswith('/admin'):
timezone.activate(pytz.timezone('EST'))
Don't forget to add that on settings.MIDDLEWARE array.
MIDDLEWARE = [
...
'yourapp.AdminTimezoneMiddleware'
]

Django DateTimeField says 'You are 5.5 hours ahead of server time.'

In one of my model I am storing time_stamp = models.DateTimeField(default=timezone.now)
But when I save the model it says You are 5.5 hours ahead of server time.
for example local time in my machine is 13:02 but after saving what gets stored in db is 7:16
I got one related here but it does not an have a satisfying answer...
models.py
class Comment(models.Model):
time_stamp = models.DateTimeField(default=timezone.now)
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.time_stamp = timezone.now()
return super(Comment, self).save(*args, **kwargs)
As you are 5.5 hrs ahead of server time, I am assuming, you are in India.
So put appriopriate timezone in settings.py
TIME_ZONE = 'Asia/Kolkata'
If somewhere else, set accordingly
Make sure you make the following change in the settings.py file in your Django project.
If it is saying that you are 5.5 hours ahead of server time. It means that you are in India then set
TIME_ZONE = 'Asia/Kolkata'
in your setting.py file.
Or check your time zone at
https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
You need to change the time zone settings on your PC and refresh. That is the only way out. I just fixed my own through that.

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, queryset, filter today

I'm trying to query the database and get the entries for today. So I got a model Events with a date time field. Just to clarify, if I remove the date filter, it does return entries from the database. If I add them it does not. I double-checked that there is an item for today.
views.py
def dashboard(request):
if request.user.is_authenticated():
now = datetime.datetime.now()
events_today = Event.objects.filter(date__year=now.year, date__month=now.month, date__day=now.day)
return render_to_response("dashboard.html", {'today': events_today,}, RequestContext(request))
Update
It does work if I change the USE_TZ to False in settings.py. But it doesn't if it's True.
Update 2
I even uploaded the project to my VPS just in case it had something to do with my computer but still the same.
Instead of datetime.datetime.now() use timezone.now():
from django.utils import timezone
timezone.now()
I think you can try this query:
events_today = Event.objects.filter(date=datetime.datetime.today())

Categories