简体   繁体   中英

Foreign key model in Django Admin

I have two user roles in Django:

  • Commercials
  • Sellers

I have created two models, Seller Model has a ForeignKey field to Commercials (every seller has a commercial related to). When I register the models in admin I can create Commercials and related sellers using StackedInline , TabularInline etc.

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 :

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 :

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.

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. 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.

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.

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嵌套内联库可能会为您提供帮助。

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