在Django模板中检查请求获取参数

时间:2016-07-08 22:27:39

标签: python django get request

我正在检查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())

2 个答案:

答案 0 :(得分:1)

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

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

此代码与原始代码之间的区别在于外if块检查order中是否存在GET,而不是评估GET.order的真实性

答案 1 :(得分:0)

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

@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参数。