Django-Admin:来自 UserProfile 的 list_filter 属性
我希望允许我的网站管理员在管理网站上过滤来自特定国家/地区的用户。因此,自然的做法是这样的:
#admin.py
class UserAdmin(django.contrib.auth.admin.UserAdmin):
list_filter=('userprofile__country__name',)
#models.py
class UserProfile(models.Model)
...
country=models.ForeignKey('Country')
class Country(models.Model)
...
name=models.CharField(max_length=32)
但是,由于 django 中处理用户及其用户配置文件的方式,这会导致以下错误:
'UserAdmin.list_filter[0]' refers to field 'userprofile__country__name' that is missing from model 'User'
如何绕过此限制?
I want to allow the admins of my site to filter users from a specific country on the Admin Site. So the natural thing to do would be something like this:
#admin.py
class UserAdmin(django.contrib.auth.admin.UserAdmin):
list_filter=('userprofile__country__name',)
#models.py
class UserProfile(models.Model)
...
country=models.ForeignKey('Country')
class Country(models.Model)
...
name=models.CharField(max_length=32)
But, because of the way Users and their UserProfiles are handled in django this leads to the following error:
'UserAdmin.list_filter[0]' refers to field 'userprofile__country__name' that is missing from model 'User'
How do I get around this limitation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在寻找的是自定义管理FilterSpecs。坏消息是,对那些可能不会很快发布的支持(您可以在此处跟踪讨论)。
然而,您可以通过肮脏的黑客攻击来解决该限制。在深入研究代码之前如何构建
FilterSpecs
FilterSpec
列表时,Django 使用您在中提供的字段列表>list_filter
FilterSpec
类列表,每个类都与一个 test 函数关联。list_filter
中的每个字段,Django 将使用第一个FilterSpec
类,对于该类,test 函数返回 True场地。好吧,现在考虑到这一点,看看下面的代码。它改编自django 片段。代码的组织由您自行决定,只需记住这应该由
admin
应用程序导入。它显然不是万能药,但它会完成这项工作,等待更好的解决方案出现。(例如,将子类化
ChangeList
并覆盖get_filters
的解决方案)。What you are looking for is custom admin FilterSpecs. The bad news is, the support for those might not supposed to ship soon (you can track the discussion here).
However, at the price of a dirty hack, you can workaround the limitation. Some highlights on how
FilterSpecs
are built before diving in the code :FilterSpec
to display on the page, Django uses the list of fields you provided inlist_filter
FilterSpec
classes, each associated with a test function.list_filter
, Django will use the firstFilterSpec
class for which the test function returns True for the field.Ok, now with this in mind, have a look at the following code. It is adapted from a django snippet. The organization of the code is left to your discretion, just keep in mind this should be imported by the
admin
app.It's clearly not a panacea but it will do the job, waiting for a better solution to come up.(for example, one that will subclass
ChangeList
and overrideget_filters
).Django 1.3 修复了它。现在允许您跨越 list_filter
https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter
Django 1.3 fixed it. You're now allowed to span relations in list_filter
https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter