Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving model instance with DateTimeField in Django Admin loses microsecond resolution

In Django 1.8, let us say we have this very simple model:

class Log(models.Model):
    remarks = models.TextField()
    timestamp = models.DateTimeField(default=timezone.now)

When I save a model instance to my PostgreSQL database, the timestamp field will have microseconds. I noticed that if I attempt to edit a particular model instance from the Django admin, the timestamp field will lose microsecond resolution when saved back into the database.

Most application would not need that level of accuracy, but for applications that do require such, it would be nice to be able to eliminate all possible causes of this loss of resolution. Is there any known way/feature to prevent this or is this a bug/limitation?

like image 976
Wannabe Coder Avatar asked Aug 20 '15 08:08

Wannabe Coder


1 Answers

The problem is that the default admin widget does not support microseconds. You can override the widget with formfield_overrides to use DateTimeInput instead, and specify a format that includes microseconds.

from django.contrib import admin
from django.db import models
from django import forms

from .models import Log

class LogAdmin(admin.ModelAdmin):

    formfield_overrides = {
        models.DateTimeField: {'widget': forms.DateTimeInput(format='%Y-%m-%d %H:%M:%S.%f')},
    }

admin.site.register(Log, LogAdmin)

In your case, since it's a timestamp, another option is to add the add the field to readonly_fields, so that it can't be changed at all.

like image 162
Alasdair Avatar answered Oct 13 '22 05:10

Alasdair