Reputation: 1409
I want to change the timezone just within the one Particular Model in Django admin, how can I do that?
As Django saves time in the database in UTC, what I want is to display the value in a particular timezone, just for one model. Not for the whole project.
For example I have a model:
class Student(models.Models)
created_at = models.DateTimeField()
When I open Django Admin for this model, I want to see the time in a particular timezone (let's say ETC) but let the Django save time in UTC.
Upvotes: 2
Views: 2030
Reputation: 1409
so I have figured out the solution: To accomplish what I wanted to accomplish I had to made changes in the ModelAdmin
class.
class StudentAdmin(Admin.ModelAdmin):
list_display = [..., "created_at_etc", ...]
def add_view(self, request, form_url='', extra_context=None):
timezone.activate("US/Eastern")
return super(ActivityAdmin, self).add_view(
request,
form_url,
extra_context
)
def change_view(self, request, object_id, form_url='', extra_context=None):
timezone.activate("US/Eastern")
return super(ActivityAdmin, self).change_view(
request,
object_id,
form_url,
extra_context
)
def get_time(self, time):
import pytz
fmt = '%Y-%m-%d %H:%M:%S %Z'
tz = pytz.timezone("US/Eastern")
dt = time.astimezone(tz)
return dt.strftime(fmt)
def created_at_etc(self, student):
return self.get_time(student.created_at)
created_at_etc.short_description = "Created At"
You can activate a particular timezone in django admin by using
from django.utils import timezone
timezone.activate("US/Eastern")
With this you can change the timezone within a context you want to. As I am doing the same in the add_view
, change_view
.
First I overrided the add_view
method that will let us create the Student
object in the particular timezone. Second I Overrided the change_view
so that we can edit the already existing Student
in the particular timezone. Third I created created_at_etc
it will display the date with respect to the particular timezone.
For more information you can use This Article.
Upvotes: 3