【问题标题】:Checking request get parameter in Django template在 Django 模板中检查请求获取参数
【发布时间】:2016-07-08 22:27:38
【问题描述】:

我正在检查 Django 模板中的 request.GET 参数。我正在粘贴其中的一部分:

<dd>
    <i class="fa fa-caret-right {% if request.GET.order %}{% ifequal request.GET.order 'price-asc' %}active{% endifequal %}{% endif %}"></i> <a href="{%url_add_replace request 'order' 'price-asc'%}">Order by price (Asc)</a>
</dd>

如您所见,还有一个名为 add_replace 的自定义模板标记。它基本上是将指定的 GET 参数添加到 url。我认为这不会造成问题。

我的问题是关于其他的。此代码在 DEBUG 级别生成日志。我正试图摆脱它。日志如下。我认为必须有更适合检查get参数是否存在的东西。我可以在以下视图中做到这一点:

get_dict = request.GET.copy()

if get_dict.__contains__('order'):
    get_order = get_dict.__getitem__('order')
else:
    get_order = None

但是当我在模板中检查它时,会出现以下日志:

DEBUG 2016-07-08 22:07:43,789 base 29571 140656761874496 Exception while resolving variable 'order' in template 'category.html'. Traceback (most recent call last):   File "/usr/local/lib/python3.5/site-packages/django/utils/datastructures.py", line 83, in __getitem__
    list_ = super(MultiValueDict, self).__getitem__(key) KeyError: 'order'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/usr/local/lib/python3.5/site-packages/django/template/base.py", line 883, in _resolve_lookup
    current = current[bit]   File "/usr/local/lib/python3.5/site-packages/django/utils/datastructures.py", line 85, in __getitem__
    raise MultiValueDictKeyError(repr(key)) django.utils.datastructures.MultiValueDictKeyError: "'order'"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/usr/local/lib/python3.5/site-packages/django/template/base.py", line 891, in _resolve_lookup
    current = getattr(current, bit) AttributeError: 'QueryDict' object has no attribute 'order'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/usr/local/lib/python3.5/site-packages/django/template/base.py", line 898, in _resolve_lookup
    current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'order'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "/usr/local/lib/python3.5/site-packages/django/template/base.py", line 905, in _resolve_lookup
    (bit, current))  # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [order] in '<QueryDict: {}>'

有什么想法吗?

更新:我正在添加自定义模板标记代码:

@register.simple_tag(name='url_add_replace')
def url_add_replace(request, field, value):

    dict = request.GET.copy()

    dict.__setitem__(field, value)

    return u"?%s" % (dict.urlencode())

【问题讨论】:

    标签: python django get request


    【解决方案1】:

    我认为自定义模板标签对此有点过分。以下模板逻辑应该可以在不触发任何调试日志的情况下工作:

    {% if 'order' in request.GET %}
        {% ifequal request.GET.order 'price-asc' %}active{% endifequal %}
    {% endif %}
    

    这与您的原始代码之间的区别在于,外部 if 块正在检查 orderGET 中的存在,而不是评估 GET.order 的真实性。

    【讨论】:

    • 感谢您的想法。我会尽快尝试并分享结果。
    【解决方案2】:

    我通过编写另一个自定义标签解决了我的问题:

    @register.simple_tag(name='active_request_get')
    def active_request_get(request, key, value):
    
        dict = request.GET.copy()
    
        if dict.__contains__(key):
    
            if dict.get(key, default=None) == value:
                return 'active'
    
        return ''
    

    我替换了这个:

    <dd>
        <i class="fa fa-caret-right {% if request.GET.order %}{% ifequal request.GET.order 'price-asc' %}active{% endifequal %}{% endif %}"></i> <a href="{%url_add_replace request 'order' 'price-asc'%}">Order by price (Asc)</a>
    </dd>
    

    用这个:

    <dd>
        <i class="fa fa-caret-right {% active_request_get request 'order' 'price-asc' %}"></i> <a href="{%url_add_replace request 'order' 'price-asc'%}">Order by price (Asc)</a>
    </dd>
    

    所以我根据需要检查 GET 参数。

    【讨论】:

      猜你喜欢
      • 2015-03-04
      • 2011-05-08
      • 2013-10-01
      • 2013-01-06
      • 1970-01-01
      • 2015-09-21
      • 2018-05-30
      • 2012-01-15
      • 1970-01-01
      相关资源
      最近更新 更多