How to populate datefield in django admin page?

1k Views Asked by At

Tried the following:

from datetime import datetime
class ArticleAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('title',), 'pub_date':(datetime.now()) }

Which raises:

ERRORS:

<class 'news.admin.ArticleAdmin'>: (admin.E028) The value of 'prepopulated_fields' refers to 'pub_date', which must not be a DateTimeField, ForeignKey or ManyToManyField.
<class 'news.admin.ArticleAdmin'>: (admin.E029) The value of 'prepopulated_fields["pub_date"]' must be a list or tuple.
2

There are 2 best solutions below

0
On

You were forgetting the comma for tuple.

from datetime import datetime
class ArticleAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('title',), 'pub_date': (datetime.now(), ) }
1
On

prepopulated_fields doesn’t accept DateTimeField, ForeignKey, nor ManyToManyField fields.

From the docs.