django admin外键字段数据添加

Neo*_*Neo 22 django django-admin

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

例如

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    contact = models.ForeignKey(Contact, blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)

对于用户和联系人字段,管理员添加表单中存在带添加按钮的下拉列表.我们可以在同一页面中拥有用户和联系人的所有字段吗?

Dar*_*ush 14

是的,您可以使用内联管理系统来实现.

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

class UserProfileAdmin(admin.ModelAdmin):
    inlines = [ UserAdmin, ContactAdmin ]
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请查看https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects .

  • 谢谢 Darioush,但它没有解决,内联管理系统适用于相反的情况,从手册中你可以看到 [link](https://docs.djangoproject.com/en/dev/ref/contrib/admin/# inlinemodeladmin-objects) 对于上述情况,如果我需要它的工作方式如下:`class UserProfileAdmin(admin.StackedInline): model = UserProfile class UserAdmin(admin.ModelAdmin): inlines = [ UserProfileAdmin ] ` 以你给出的方式给出错误 `<class 'profiles.models.Contact'> has no ForeignKey to <class 'profiles.models.UserProfile'>` (2认同)

lyn*_*ynx 5

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

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

-e git+https://github.com/anziem/django_reverse_admin.git#egg=django_reverse_admin
Run Code Online (Sandbox Code Playgroud)

然后导入:

管理文件

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)
Run Code Online (Sandbox Code Playgroud)