简体   繁体   English

Django Admin中的外键模型

[英]Foreign key model in Django Admin

I have two user roles in Django: 我在Django中有两个用户角色:

  • Commercials 商业广告
  • Sellers 卖家

I have created two models, Seller Model has a ForeignKey field to Commercials (every seller has a commercial related to). 我创建了两个模型,卖方模型有一个指向Commercials的ForeignKey字段(每个卖方都有与之相关的广告)。 When I register the models in admin I can create Commercials and related sellers using StackedInline , TabularInline etc. 当我在admin中注册模型时,可以使用StackedInlineTabularInline等创建广告和相关卖家。

The problem I have is I need to associate users to this models in order to authenticate, login, etc. In admin I need to create a user (in an inline way, not dropdown box) 我的问题是我需要将用户与该模型关联以便进行身份验证,登录等。在管理员中,我需要创建一个用户(以内联方式,而不是下拉框)

This is my code: 这是我的代码:

In models.py : models.py中

class Commercial(models.Model):
    name = models.CharField(max_length=255, null=True)
    user = models.OneToOneField(User, null=True)


class Seller(models.Model):
    name = models.CharField(max_length=255, null=True)
    commercial = models.ForeignKey('Commercial')
    user = models.OneToOneField(User, null=True)

In admin.py : admin.py中

class SellerAdmin(admin.StackedInline):
    model = Seller
    extra = 1

class CommercialAdmin(admin.ModelAdmin):
   inlines = [SellerAdmin]

admin.site.register(Commercial, CommercialAdmin)

I need to edit, create, users etc. related to this models inline not in a modal window, Is there any way? 我需要在模态窗口中内联编辑,创建,与该模型相关的用户等,请问有什么办法吗?

在此处输入图片说明

There is no way to make a reverse relation (so to say) in the form of Inlines. 没有办法以内联形式建立反向关系(可以这么说)。 The Django admin panel doesn't have that ability by default. Django管理面板默认没有该功能。

What you could do is unregister the default UserAdmin, create a new Admin panel by inheriting the original one, and add this Seller as an Inline. 您可以做的是取消注册默认的UserAdmin,通过继承原始UserAdmin创建一个新的Admin面板,然后将此卖方添加为Inline。 There is still the issue that Django doesn't support multiple inlines, hence, you will not be able to use the Commercial model in the same admin page. 仍然存在Django不支持多个内联的问题,因此,您将无法在同一管理页面中使用Commercial模型。

To fix that, you could refer to this information from the doc which shows how to overwrite the automatically created ModelForm for a particular ModelAdmin. 要解决此问题,您可以参考文档中的此信息,该文档显示了如何为特定的ModelAdmin覆盖自动创建的ModelForm。

This will however not be that helpful as they are a lot of work. 但是,由于它们需要大量工作,因此不会有太大帮助。 I would rather suggest implementing a workaround in how your application is used, rather than complicating it this much. 我宁愿建议在应用程序的使用方式上实现一种变通方法,而不是使它复杂化。 Depends on the needs of the project, whether you need to go through this much trouble 取决于项目的需求,是否需要经历这么多麻烦

Django嵌套内联库可能会为您提供帮助。

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

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