【问题标题】:Editing/Adding a Foreign Key object through inline display in the Django Admin通过 Django Admin 中的内联显示编辑/添加外键对象
【发布时间】:2015-03-20 12:05:55
【问题描述】:

我的 Complete_Book 模型具有 Book 的外键。书是我从已安装的应用程序中使用的东西(因此,一个“外部应用程序”)我希望能够直接从 Complete_Book 管理员编辑/创建一个“书”。这可能吗?我无法使用内联,因为我的外键关系是内联允许的“倒退”。

我的问题与此问题 (Django admin inline display but foreign key has opposite relation) 中解释的问题相同,但我无法按照该答案中的建议重构我的模型。还有其他方法吗?感谢您的帮助!

models.py

class Complete_Book(models.Model):
    topic = models.ForeignKey('topic')
    book = models.ForeignKey(Book)
    is_primary = models.BooleanField()
    subprogram_name = models.CharField(max_length = 256, blank=True)

class Book(models.Model):
    title = models.CharField(max_length=512)
    authors = models.CharField(max_length=2048)
    year = models.PositiveIntegerField(max_length=4)

【问题讨论】:

    标签: django django-admin


    【解决方案1】:

    django_reverse_admin 是一个 django 模块,用于解决需要内联关系是“错误”方向的问题。

    您需要将其添加到您的 requirements.txt 中,然后将其导入:

    admin.py

    from django_reverse_admin import ReverseModelAdmin
    
    class Complete_Book(ReverseModelAdmin):
        # usual admin stuff goes here
        inline_type = 'tabular'  # or could be 'stacked'
        inline_reverse = ['book']  # could do [('book', {'fields': ['title', 'authors'})] if you only wanted to show certain fields in the create admin
    
    admin.site.register(Book, Complete_Book)
    

    【讨论】:

      【解决方案2】:

      是的,这实际上很容易。只需确保为 Book 注册 ModelAdmin,管理员将向 Complete_Book 管理员添加一个 + 按钮,以便您创建新书。

      【讨论】:

      • 抱歉,我不清楚 - 我的意思是我希望能够在同一个窗口中编辑/添加新的图书信息。我不想单击“+”然后被带到一个新窗口...我希望 Book 字段(标题、作者、年份)与 Complete_Book 字段一起显示...?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 2011-02-01
      • 2012-06-09
      • 2012-08-10
      • 2013-02-26
      相关资源
      最近更新 更多