You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用DateTimeField(auto_now_add=True,null=True)后Django后台不显示时间

Fixing Django DateTimeField Not Showing in Admin Panel

Got it, let's troubleshoot why your DateTimeField(auto_now_add=True, null=True) isn't showing up in the Django admin. I’ve dealt with this exact scenario a few times, so here are the most straightforward fixes to try:

1. Add the field to your Admin class's list_display or readonly_fields

By default, Django’s admin only shows fields you explicitly list in list_display (or just the model’s __str__ output if you don’t set this). Plus, fields with auto_now_add=True are automatically marked as editable=False, which hides them from the edit form by default.

To make it visible in the admin list view:

from django.contrib import admin
from .models import YourModel  # Replace with your actual model name

class YourModelAdmin(admin.ModelAdmin):
    # Add your datetime field to the list of displayed fields
    list_display = ('id', 'some_other_field', 'your_datetime_field')

admin.site.register(YourModel, YourModelAdmin)

To show it as a read-only field in the edit form (since you can’t edit a field with auto_now_add=True anyway):

class YourModelAdmin(admin.ModelAdmin):
    list_display = ('id', 'some_other_field', 'your_datetime_field')
    # Mark the field as read-only to display it in the edit view
    readonly_fields = ('your_datetime_field',)

2. Double-check for typos in the field name

It sounds silly, but it’s easy to mistype the field name in the Admin class. Make sure the name you’re using in list_display or readonly_fields matches exactly what’s defined in your model (capitalization and all).

3. Optional: Clean up your field definition

While this isn’t causing the visibility issue, null=True is unnecessary with auto_now_add=True—this field will always get a value when the object is created. You can safely remove null=True and even add blank=True if you want (though auto_now_add handles the value automatically):

created_at = models.DateTimeField(auto_now_add=True, blank=True)

4. Refresh and restart if needed

Sometimes browser cache can make it look like changes aren’t applied. Hit Ctrl+F5 to force a full page refresh, or restart your Django dev server to ensure your code updates are loaded.

内容的提问来源于stack exchange,提问作者Milan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 13:52:34