[Fixed]-Saving model instance with DateTimeField in Django Admin loses microsecond resolution

9👍

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.

Leave a comment