简体   繁体   English

管理员中的Django OneToOne字段

[英]Django OneToOne field in admin

Here is a model in Django: 这是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. 我想将所有用户字段放在Django管理员的该模型的“编辑/创建”页面中。 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. 但是Django表示User上没有Member的外键,这是完全正确的。 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. 如果我不使用admin类,那么我得到的只是一个可供选择的用户列表。

Ideally, I'd like the User type to be invisible to administrators and have them only create and edit derived User types. 理想情况下,我希望管理员不能看到User类型,并让他们仅创建和编辑派生的用户类型。

Instead of a OneToOne relation, should I be extending the actual User type instead? 我应该扩展实际的User类型,而不是OneToOne关系吗?

As we discussed in the chat, the built-in User object is meant to be used in the admin site. 正如我们在聊天中所讨论的,内置的User对象旨在在管理站点中使用。 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: 为此,您需要子类AbstractBaseUser并按照此处的说明进行操作:

https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model 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 它确实非常详细,如果您遇到任何麻烦,请回到这里,以便有人一定会为您提供帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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