django管理外键字段数据添加

django管理外键字段数据添加,django,django-admin,Django,Django Admin,在django admin中任何应用程序的添加表单中,该模型的外键字段。。带有“添加”按钮的下拉列表(在弹出窗口中打开)。我们可以有一个表单,在这个表单中我们可以以相同的形式添加外键模型字段 例如 class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) contact = models.ForeignKey(Contact, blank=True, null=True) 对于“用户

在django admin中任何应用程序的添加表单中,该模型的外键字段。。带有“添加”按钮的下拉列表(在弹出窗口中打开)。我们可以有一个表单,在这个表单中我们可以以相同的形式添加外键模型字段

例如

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    contact = models.ForeignKey(Contact, blank=True, null=True)

对于“用户”和“联系人”字段,“管理员添加”表单中有一个带有“添加”按钮的下拉列表。我们是否可以将“用户”和“联系人”的所有字段都放在同一页面中?

是的,您可以使用内联管理系统进行此操作

class UserAdmin(admin.StackedInline):
    model = User
class ContactAdmin(admin.StackedInline):
    model = Contact

class UserProfileAdmin(admin.ModelAdmin):
    inlines = [ UserAdmin, ContactAdmin ]
有关更多详细信息,请查看
.

在这种情况下,如果关系与通常相反,则有一个django插件可以获取内联线:

您需要将django_reverse_admin添加到requirements.txt:

-e git+https://github.com/anziem/django_reverse_admin.git#egg=django_reverse_admin
然后导入它:

管理员

from django_reverse_admin import ReverseModelAdmin

class UserProfileAdmin(ReverseModelAdmin):
    inline_reverse = ['user', 'contact']
    inline_type = 'tabular'  # or could be 'stacked'

admin.site.register(UserProfile, UserProfileAdmin)

谢谢Darioush,但它没有工作,内联管理系统适用于相反的情况,从手册中可以看到,如果我需要的话,它适用于上面的情况:
class UserProfileAdmin(admin.StackedInline):model=UserProfile class UserAdmin(admin.ModelAdmin):inlines=[UserProfileAdmin]
按照您给出的方式,它给出了一个错误
没有外键
对不起,我的错。显然,没有简单的方法来实现这一点,有关更多信息,请参阅