Django管理接口:使用带有内联manytomyne字段的水平过滤器

2024-05-16 20:56:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

目前,我已经让“表格”内联视图工作。有没有一种方法可以有一个“水平过滤器”,以便我可以轻松地添加和删除项目从用户配置文件?

请参阅所附图片以获取示例。enter image description here

以下是用户配置文件的模型代码:

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.")

以及项目的模型代码:

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()

以及视图的管理代码:

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)

Tags: 项目代码用户name模型projecttrueapplication
2条回答

问题不在于有内联;而在于一般情况下,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
    ...

也许可以稍微走一走。首先,我们定义一个userprofiles表单字段。它将使用一个ModelMultipleChoiceField,这在默认情况下将导致一个多选框。因为这不是模型上的实际字段,所以我们不能将它添加到filter_horizontal,而是告诉它只使用相同的小部件FilteredSelectMultiple,如果它列在filter_horizontal中,它将使用这个小部件。

我们最初将queryset设置为整个UserProfile集,但您不能在这里过滤它,因为在类定义的这个阶段,表单尚未实例化,因此还没有instance集。因此,我们重写__init__,以便可以将筛选后的queryset设置为字段的初始值。

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

在处理自身的多对多关系时的一个小附加。人们可能希望将自己排除在选择之外:

if self.instance.pk:
        self.fields['field_being_added'].queryset = self.fields['field_being_added'].queryset.exclude(pk=self.instance.pk)
        self.fields['field_being_added'].initial = """Corresponding result queryset"""

相关问题 更多 >