Django管理界面:使用horizo​​ntal_filter和内联ManyToMany字段

Dyl*_*ens 21 python django django-admin

我有一个Django模型字段,我想内联.该领域是一种多对多的关系.所以有"项目"和"用户档案".每个用户配置文件可以选择任意数量的项目.

目前,我有"表格式"内联视图工作.有没有办法有一个"水平过滤器",以便我可以轻松地添加和删除用户配置文件中的项目?

请参阅附图以获取示例.在此输入图像描述

这是用户配置文件的型号代码:

class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True)
    projects = models.ManyToManyField(Project, blank=True, help_text="Select the projects that this user is currently working on.")
Run Code Online (Sandbox Code Playgroud)

和项目的模型代码:

class Project(models.Model):
    name = models.CharField(max_length=100, unique=True)
    application_identifier = models.CharField(max_length=100)
    type = models.IntegerField(choices=ProjectType)
    account = models.ForeignKey(Account)
    principle_investigator = models.ForeignKey(User)
    active = models.BooleanField()
Run Code Online (Sandbox Code Playgroud)

以及视图的管理代码:

class UserProfileInline(admin.TabularInline):
    model = UserProfile.projects.through
    extra = 0
    verbose_name = 'user'
    verbose_name_plural = 'users'

class ProjectAdmin(admin.ModelAdmin):
    list_display = ('name', 'application_identifier', 'type', 'account', 'active')
    search_fields = ('name', 'application_identifier', 'account__name')
    list_filter = ('type', 'active')
    inlines = [UserProfileInline,]
admin.site.register(Project, ProjectAdmin)
Run Code Online (Sandbox Code Playgroud)

Chr*_*att 45

问题不在于内联; ModelForm总的来说,它来自工作方式.它们仅为模型上的实际字段构建表单字段,而不是相关的管理器属性.但是,您可以将此功能添加到表单:

from django.contrib.admin.widgets import FilteredSelectMultiple

class ProjectAdminForm(forms.ModelForm):
    class Meta:
        model = Project

    userprofiles = forms.ModelMultipleChoiceField(
        queryset=UserProfile.objects.all(),
        required=False,
        widget=FilteredSelectMultiple(
            verbose_name='User Profiles',
            is_stacked=False
        )
    )

    def __init__(self, *args, **kwargs):
        super(ProjectAdminForm, self).__init__(*args, **kwargs)
            if self.instance.pk:
                self.fields['userprofiles'].initial = self.instance.userprofile_set.all()

    def save(self, commit=True):
        project = super(ProjectAdminForm, self).save(commit=False)  
        if commit:
            project.save()

        if project.pk:
            project.userprofile_set = self.cleaned_data['userprofiles']
            self.save_m2m()

        return project

class ProjectAdmin(admin.ModelAdmin):
    form = ProjectAdminForm
    ...
Run Code Online (Sandbox Code Playgroud)

可能需要一点点演练.首先,我们定义一个userprofiles表单字段.它将使用a ModelMultipleChoiceField,默认情况下会产生一个多选框.由于这不是模型上的实际字段,我们不能只将其添加到filter_horizontal,因此我们告诉它只使用相同的小部件,FilteredSelectMultiple如果它被列在其中,它将使用filter_horizontal.

我们最初将查询集设置为整个UserProfile集合,您无法在此处对其进行过滤,因为在类定义的此阶段,表单尚未实例化,因此instance尚未设置它.因此,我们重写,__init__以便我们可以将过滤的查询集设置为字段的初始值.

最后,我们重写该save方法,以便我们可以将相关管理器的内容设置为与表单的POST数据相同,然后就完成了.