Django admin inline model for User

2020-05-28 02:06发布

I have model as

class Employer(models.Model):
    create_user = models.ForeignKey(User,unique=False,null=True, related_name='%(class)s_user_create')
    update_user = models.ForeignKey(User,unique=False,null=True, related_name='%(class)s_user_update')

and I would like to list all Employer objects while I was at details of user in Django admin panel.

I have written something like

admin.py

class EmployerInline(admin.TabularInline):
    model = Employer

class UserAdmin(admin.ModelAdmin):
    inlines = [
               EmployerInline
    ]

admin.site.register(UserAdmin)

but it gives me error as 'MediaDefiningClass' object is not iterable

How can I list employers that are created by a spesific user while I was looking for user's details ?

Thanks

1条回答
Viruses.
2楼-- · 2020-05-28 02:11

The particular error you mention doesn't seem to have anything to do with what's going on in your code, so I'm not sure about that particularly. However, you have other errors here, so potentially fixing those will resolve that error as well.

First, you need to specify fk_name on your EmployerInline. Django resolves the foreign key automatically in most circumstances, but since you have two foreign keys to the same model, you have to give Django some help.

class EmployerInline(admin.TabularInline):
    model = Employer
    fk_name = 'create_user'

Second, you may have just omitted it, but you must unregister User before registering it. You also need to specify the model when registering:

admin.site.unregister(User)
admin.site.register(User, UserAdmin)
查看更多
登录 后发表回答