我有一个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.")
以及项目的模型代码:
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)
问题不在于有内联;而在于一般情况下,
ModelForm
的工作方式。它们只为模型上的实际字段构建表单字段,而不是相关的管理器属性。但是,您可以将此功能添加到表单中:也许可以稍微走一走。首先,我们定义一个
userprofiles
表单字段。它将使用一个ModelMultipleChoiceField
,这在默认情况下将导致一个多选框。因为这不是模型上的实际字段,所以我们不能将它添加到filter_horizontal
,而是告诉它只使用相同的小部件FilteredSelectMultiple
,如果它列在filter_horizontal
中,它将使用这个小部件。我们最初将queryset设置为整个
UserProfile
集,但您不能在这里过滤它,因为在类定义的这个阶段,表单尚未实例化,因此还没有instance
集。因此,我们重写__init__
,以便可以将筛选后的queryset设置为字段的初始值。最后,我们重写
save
方法,以便我们可以将相关管理器的内容设置为与表单的POST数据中的内容相同,这样就完成了。在处理自身的多对多关系时的一个小附加。人们可能希望将自己排除在选择之外:
相关问题 更多 >
编程相关推荐