新手最近做个项目,文章要从用户表里选5位,具有特定权限的用户做评委,官网找到formfield_for_manytomany方法,但使用该方法后filter_horizontal会横向展示会失效,两者不能共存。请教大神有没有解决办法,或者有没有类似功能实现。
class ProjectAdmin(admin.ModelAdmin):
readonly_fields = ('user',)
list_display = ['id', 'project_name', 'user', 'project_type', 'create_time']
search_fields = ('project_name', 'project_desc')
filter_horizontal = ('judges',)
# raw_id_fields = ('judges',)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
if db_field.name == "judges":
kwargs["queryset"] = models.User.objects.filter(post=2)
return super(ProjectAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
def formfield_for_manytomany(self, db_field, request, kwargs):
"""
Get a form Field for a ManyToManyField.
"""
# db_field.nam 本模型下的字段名称
if db_field.name == "tags":
kwargs["queryset"] = Tag.objects.filter(show_status=True)
from django.contrib.admin import widgets
kwargs['widget'] = widgets.FilteredSelectMultiple(
db_field.verbose_name,
db_field.name in self.filter_vertical
)
return super(ArticleAdmin, self).formfield_for_foreignkey(db_field, request, kwargs)
虽然过去快一年了,但还是完美问题,非常感谢!
在return前加上,造福后人。
from django.contrib.admin import widgets
kwargs['widget'] = widgets.FilteredSelectMultiple(
db_field.verbose_name,
db_field.name in self.filter_vertical
)
@不识少年愁: 嗯,我昨天也想达到你这个效果,搜索到你的文章,再然后看了下源码找到了保持横向展示的代码。我已经写到我的博客了,标题:Django admin 多对多字段 过滤方法 及 保持横向显示
链接:https://xieboke.net/article/242/
请问一下在穿梭框内怎么实现搜索功能,我指定了搜索字段,好像没有效果