Django Admin:如何访问 admin.py 中的请求对象,以获取 list_display 方法? [英] Django Admin: How to access the request object in admin.py, for list_display methods?

查看:16
本文介绍了Django Admin:如何访问 admin.py 中的请求对象,以获取 list_display 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模型的 admin.py 类中添加了一个方法 highlight_link:

I've added a method highlight_link to my model's admin.py class:

class RadioGridAdmin(admin.ModelAdmin):
    
    list_display = ('start_time', highlight_link)
    
    def highlight_link(self):
        return ('some custom link')
    
    
admin.site.register(RadioGrid, RadioGridAdmin)

它为更改列表中返回的每条记录返回一个自定义链接(为简洁起见,我省略了highlight_link.short_description).这很棒.但我想检查当前的查询字符串并根据它更改自定义链接.有没有办法在 highlight_link 中访问请求对象?

It returns a custom link for (I've left out highlight_link.short_description for brevity) each record returned in the change list. Which is great. But I'd like to inspect the current query string and change the custom link based on that. Is there a way to access the request object within highlight_link?

推荐答案

我尝试了这里留下的其他答案,但遇到了对我来说越来越复杂的问题.我玩弄了 def __call__() 并想出了以下内容.这可能不是正确的方法,但它有效......

I tried the other answers left here and ran into issues that for me, were getting complex. I played around with def __call__() and came up with the following. This probably isn't the correct way to do this, but it works...

在这里获取 GET 变量(所有都在我最初的帖子中描述的 RadioGridAdmin 类中):

grab the GET variable here (all within class RadioGridAdmin as described above in my initial post):

def __call__(self, request, url):
     global start_date
     start_date = request.GET['param']

     return super(RadioGridAdmin, self).__call__(request, url)

而且由于它是全球性的,您现在可以在这里访问它:

and since it's global, you can now access it here:

def highlight_link(self):
    # access start_date here

这篇关于Django Admin:如何访问 admin.py 中的请求对象,以获取 list_display 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆