Default (initial) value in Django's admin for a choice field

I was trying to set the initial value for a choice field in the admin like this:

from django import forms
from django.contrib import admin
from mptt.admin import MPTTModelAdmin
from author.models import Author
from serials.constants import STATUS_CHOICES

class AuthorAdminForm(forms.ModelForm):
    class Meta:
        model = Author

class AuthorAdmin(MPTTModelAdmin):
    form = AuthorAdminForm(initial={'status': STATUS_CHOICES[0][0]})
admin.site.register(Author, AuthorAdmin)

Logically, I should have been able to do it this way, I thought, at least according to the docs. But instead it was giving me this error: TypeError: issubclass() arg 1 must be a class. (Uh, ok.) After a bit of searching, I eventually found this comment, and realized I must be trying to instantiate a form that the admin would instantiate automatically, had already been instantiated, or something like that pharmacieviagra.com.

After some more searching, I found the answer on the way to do what I needed here:

from django import forms
from django.contrib import admin
from mptt.admin import MPTTModelAdmin
from author.models import Author
from serials.constants import STATUS_CHOICES

class AuthorAdminForm(forms.ModelForm):
    class Meta:
        model = Author

    def __init__(self, *args, **kwargs):
        super(AuthorAdminForm, self).__init__(*args, **kwargs)
        self.initial['status'] = STATUS_CHOICES[0][0]
            
class AuthorAdmin(MPTTModelAdmin):
    form = AuthorAdminForm
admin.site.register(Author, AuthorAdmin)

Yay! Hope this helps someone else who has the same issue. :)

One Comment

  1. kliyes says:

    You saved my time buddy! I struggled with this:

    self.fields['status'].initial = 'value'

    and not any effect before I found your post.

    Thanks a lot!

Leave a Reply