简体   繁体   中英

Django OneToOne field in admin

Here is a model in Django:

class Member(models.Model):
    user     = models.OneToOneField(User)
    moredata = models.CharField('More data', max_length=255)

I want to put all the user fields in that model's edit/create page in the Django admin. So I did this:

class UserInline(admin.StackedInline):
    model = User

class MemberAdmin(admin.ModelAdmin):
    inlines = [
        UserInline,
    ]

admin.site.register(Member, MemberAdmin)

But Django says that there are no foreign keys to Member on User, which is completely true. Is there a way to fix this?

If I don't use the admin class, all I get is a list of users to pick from.

Ideally, I'd like the User type to be invisible to administrators and have them only create and edit derived User types.

Instead of a OneToOne relation, should I be extending the actual User type instead?

As we discussed in the chat, the built-in User object is meant to be used in the admin site. But in your case, it is irrelevent to your models, and only adds limitations and complications.

In that case, the best approach would be to use your own models as independent user classes and use the built-in User for the admin (or not at all). To do that you need to subclass the AbstractBaseUser and follow the instructions here:

https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model

It's really very detailed, and if you face any trouble with it, come back here to SO someone will surely help with that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM