简体   繁体   English

Django 如何在模板中查找querydict?

[英]Django How to Look up querydict in template?

when i look inside querydict it with {{get_copy}} it shows当我用{{get_copy}}查看 querydict 时,它显示

<QueryDict: {'grub_id__in': ['Yelek', 'Tunik', 'Tulum', 'Tshirt']}>

as i know that how to look up querydict据我所知,如何查找 querydict

{%for key,val in get_copy.items%}
{{key}}{{val}}
{%endfor%}

but it shows only one of val value但它只显示一个 val 值

output: output:

grub_id__in Tshirt

From the QueryDict.items() ofQueryDict objects[Django-doc]来自 QueryDict 对象的QueryDict.items()[Django-doc]

Like dict.items(), except this uses the same last-value logic as getitem () and returns an iterator object instead of a view object.dict.items () 类似,除了它使用与 getitem() 相同的最后值逻辑并返回迭代器 object 而不是视图 object。

And the QueryDict.__getitem__(key) as statedQueryDict.__getitem__(key)

Returns the value for the given key.返回给定键的值。 If the key has more than one value, it returns the last value .如果键有多个值,则返回最后一个值 Raises django.utils.datastructures.MultiValueDictKeyError if the key does not exist.如果密钥不存在,则引发 django.utils.datastructures.MultiValueDictKeyError。

So you can use QueryDict.getlist(key, default=None) as stated所以你可以按照说明使用QueryDict.getlist(key, default=None)

Returns a list of the data with the requested key.返回具有请求键的数据列表。 Returns an empty list if the key doesn't exist and default is None.如果键不存在且默认为 None,则返回一个空列表。 It's guaranteed to return a list unless the default value provided isn't a list.它保证返回一个列表,除非提供的默认值不是列表。

In your views.py在你的views.py

from django.http import QueryDict
from django.shortcuts import render

def get_copy(request):
    data = QueryDict('grub_id__in=Yelek&grub_id__in=Tunik&grub_id__in=Tulum&grub_id__in=Tshirt')
    return render(request, 'test.html', {'get_copy':data.getlist('grub_id__in')})

And in your templates在你的templates

{{get_copy}}

Output Output

['Yelek', 'Tunik', 'Tulum', 'Tshirt']

Add space befor/after "%": {%_.... _%}在“%”之前/之后添加空格:{%_.... _%}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM