fieryred
fieryred

Reputation: 105

How to prepopulate UserProfile fields in the Django admin?

Prepopulating most model fields in the admin (useful for generating slugs) seems to be straightforward if you use:

prepopulated_fields = {"slug": ("name",)}  

But when I use the code below to try to prepopulate a UserProfile field, it gives this error message, even though I clearly have a slug in the UserProfile model. (It's just looking in the wrong model and I don't know how to fix this...)

ERROR:

ImproperlyConfigured at /admin/
'UserProfileAdmin.prepopulated_fields' refers to field 'slug' that is missing from model 'User'.

In settings.py:

AUTH_PROFILE_MODULE = 'myapp.UserProfile'

In models.py:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    slug = models.SlugField(max_length=50)

In admin.py:

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    max_num = 1
    can_delete = False

class UserProfileAdmin(admin.ModelAdmin):
    inlines = [UserProfileInline]
    prepopulated_fields = {"slug": ("name",)}

admin.site.unregister(User)
admin.site.register(User, UserProfileAdmin)  

Can anyone spot reason for the error here?

Upvotes: 1

Views: 2412

Answers (1)

jammon
jammon

Reputation: 3464

slug is a field in UserProfile, but the prepopulated_fields = {"slug": ("name",)} is an attribute of UserProfileAdmin, which is applied to User.

prepopulated_fields triggers some javascript that autogenerates the value of a SlugField out of the values of some other fields of the same model. What you are trying is to prepopulate a field of a different model. The UserProfileAdmin is applied to User, the prepopulated_fields refers to the field slug which is unknown to the model User. It is defined in UserProfile.

That's why I think that the biggest problem here is the name UserProfileAdmin which should rather be UserAdmin. Don't confuse the model to which the prepopulated_fields is applied with the one that is inlined. Even when there is a OneToOne relation, it still is a different model.

Upvotes: 2

Related Questions