使用DateTimeField(auto_now_add=True,null=True)后Django后台不显示时间
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

