【发布时间】: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())
【问题讨论】: