简体   繁体   English

添加/更改表单中的ForeignKey字段 - Django admin

[英]ForeignKey fields in add/change forms - Django admin

Say I have these models as a simple example: 假设我将这些模型作为一个简单的例子:

class Event(models.Model):
    name = models.CharField(max_length=50, default='')
    app = models.ForeignKey(App)

class App(models.Model):
    name = models.CharField(max_length=50, default='')
    app_config = models.ForeignKey(AppConfig)

class AppConfig(models.Model):
    type = models.CharField(max_length=50, default='')
    is_valid = models.BooleanField(default=True)

I want to create an Admin page with add/change forms for Event that will allow me to select an App and create AppConfig with all its fields. 我想创建一个Admin页面,其中包含Event添加/更改表单,这将允许我选择一个App并创建包含其所有字段的AppConfig

Basically, to have a form with a dropdown to choose an App and below it a form to fill in the AppConfig fields. 基本上,要有一个带有下拉列表的表单来选择一个App ,在它下面有一个表单来填写AppConfig字段。 Or even just a "+" sign or a link that will popup a form to create an AppConfig . 或者甚至只是一个“+”符号或弹出表单来创建AppConfig

I saw many examples of how to add this to the list_display (such as this ) but couldn't manage to do the same with fields or fieldsets in order to have it in the add/change form as well. 我看到的是如何把它添加到许多例子list_display (如 ),但也无法做到与同一fieldsfieldsets ,以便把它在添加/修改的形式为好。

Any suggestions will be appreciated. 任何建议将不胜感激。 Thanks! 谢谢!

Note: I know that this might be easily solved if I also had AppConfig as a foreign key in Event but this doesn't really make sense. 注:我知道这可能是很容易解决,如果我也有过AppConfig作为一个外键Event ,但是这并没有真正意义。

Edit: My Django and Python versions: 编辑:我的Django和Python版本:
Python: 2.7.x Python:2.7.x
Django: 1.7.4 Django:1.7.4

Edit2: I have found this nice open-source code django_reverse_admin which might be helpful, but first, this specific package support only Django 2.0+. Edit2:我发现这个很好的开源代码django_reverse_admin可能会有所帮助,但首先,这个特定的软件包只支持Django 2.0+。 I tried to use the original code which does seem to support previous Django versions but didn't manage to apply it to my specific case. 我试图使用原来的代码,似乎支持以前的Django版本,但没有设法将其应用于我的具体情况。
If anyone have an idea or can show me how to use this in my specific case it will be great. 如果有人有想法或者可以告诉我如何在我的特定情况下使用它,这将是伟大的。 Thanks! 谢谢!

This package allows you to quickly filter or group "chained" models by adding a custom foreign key or many to many field to your models. 通过此软件包,您可以通过向模型添加自定义外键或多个字段来快速筛选或分组“链式”模型。 This will use an AJAX query to load only the applicable chained objects. 这将使用AJAX查询仅加载适用的链接对象。

https://github.com/digi604/django-smart-selects https://github.com/digi604/django-smart-selects

I think, the solution is already talked here How to filter a dropdownlist in Django's admin when a selection is made on another dropdownlist 我想,这里已经讨论了解决方案如何在另一个下拉列表中进行选择时过滤Django管理员中的下拉列表

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

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