Django - 从自定义过滤器中访问RequestContext [英] Django - accessing the RequestContext from within a custom filter

查看:100
本文介绍了Django - 从自定义过滤器中访问RequestContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个过滤器货币,以USD为单位,并将其转换为货币(美元或英镑)。要转换的货币存储在会话中,但是过滤器不采取 RequestContext ,所以我不能直接从那里抓取。

I've got a filter currency, which takes a value in USD and converts it to a currency (either USD or GBP). The currency to convert to is stored in the session, but filters don't take RequestContext, so I can't grab it straight from there.

有没有比将相关会话元素传递到模板更好的方法,而从模板到过滤器作为参数?虽然这种方法是有效的,但似乎相当可怕,我可能会将货币通过(几乎)每个模板。

Is there a better way than passing the relevant session element into the template, and from the template into the filter as an argument? Whilst this approach is working, it seems fairly horrible, and I'm likely to end up passing the currency to (almost) every template.

我的过滤器目前看起来像这个:

My filter currently looks something like this:

def currency(value, currency):
    if currency == 'usd':
       val = '$%.2f' % value
       return mark_safe(val)

    d = Decimal(value)
    val = '£%.2f' % (d*Decimal('0.63'))

    return mark_safe(val)


推荐答案

如果您创建一个模板标签而不是过滤器,那么您将获得使用的上下文(包含请求)。 http://docs.djangoproject。 com / en / dev / howto / custom-template-tags /#writing-custom-template-tags

If you create a template tag instead of a filter, you are given the context to work with (which contains the request). http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags

这篇关于Django - 从自定义过滤器中访问RequestContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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