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'
]
Related
I tried django-tz-detect but it's not working in production. I also tried django-easy-timezones module that's also not working for me.
I just want to convert UTC timezone to users country's timezone like Twitter or other social media in Django.
One way to this is by using the Freegeoip API. It provides us with 10,000 requests per hour by default.
Step 1: Get user timezone:
import requests
freegeoip_response = requests.get('http://freegeoip.net/json')
freegeoip_response_json = freegeoip_response.json()
user_time_zone = freegeoip_response_json['time_zone']
Setp 2: Activate Timezone
import pytz
from django.utils import timezone
....
timezone.activate(pytz.timezone(user_time_zone))
You can add middleware like this aswell:
class UserTimezoneMiddleware(object):
""" Middleware to check user timezone. """
def process_request(self, request):
user_time_zone = request.session.get('user_time_zone', None)
try:
if user_time_zone is None:
freegeoip_response = requests.get('http://freegeoip.net/json/{0}'.format(ip))
freegeoip_response_json = freegeoip_response.json()
user_time_zone = freegeoip_response_json['time_zone']
if user_time_zone:
request.session['user_time_zone'] = user_time_zone
timezone.activate(pytz.timezone(user_time_zone))
except:
pass
return None
For more help: Visit Here
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
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'
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}}
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.