Home > Blockchain >  Django How to Look up querydict in template?
Django How to Look up querydict in template?

Time:02-12

when i look inside querydict it with {{get_copy}} it shows

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

as i know that how to look up querydict

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

but it shows only one of val value

output:

grub_id__in Tshirt

CodePudding user response:

Add space befor/after "%": {%_ .... _%}

CodePudding user response:

From the QueryDict.items() of QueryDict objects[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.

And the QueryDict.__getitem__(key) as stated

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.

So you can use QueryDict.getlist(key, default=None) as stated

Returns a list of the data with the requested key. Returns an empty list if the key doesn’t exist and default is None. It’s guaranteed to return a list unless the default value provided isn’t a list.

In your 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

{{get_copy}}

Output

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