Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing QueryDict element from response.POST.get() in Django template

Tags:

python

django

Here's my page:

<p>Request as string: {{ request.POST }}</p>

Which correctly renders:

Request as string: <QueryDict: {'csrfmiddlewaretoken': ['HPOQ0pfVf5DU0Lkz05IXqbECipdPUOcTiNGYWd4giZC7LVL5Y6jdT0nb0AcmX9pd'], 'txtNumBins': ['3']}>

I'm trying to access the list txtNumBins. But when I try any of the following in my Django template:

<p>Total bins: {{  request.POST['txtNumBins'][0]  }} </p> 
<p>Total bins: {{  request.POST.get('txtNumBins')[0]  }} </p> 
<p>Total bins: {{  request.POST['txtNumBins']  }} </p> 
<p>Total bins: {{  request.POST.get('txtNumBins')  }} </p> 

I keep getting an identical error:

TemplateSyntaxError at /analysis/
Could not parse the remainder: '['txtNumBins'][0]' from'request.POST['txtNumBins'][0]'

How do I access the dictionary element txtNumBins by name?

like image 482
Shaun Overton Avatar asked Oct 26 '25 23:10

Shaun Overton


2 Answers

As you have found, you can't by default use function calls, dictionary access by key, or list indexing inside of templates. You would probably be better off getting this information in your view, and passing it as part of the response context. For example:

def my_view(request):
    total_bins = request.POST['txtNumBins'][0]
    return render(request, 'my_template.html', {'total_bins': total_bins})

Then in your template you can do:

<p>Total bins: {{ total_bins  }}</p>
like image 51
elethan Avatar answered Oct 28 '25 12:10

elethan


The Django template language is not Python. You can't call functions like get() with arguments, or use square brackets for dictionary/index lookups. Instead, you use dot for dictionary/index lookups as well as attribute lookups.

In this case, you want:

{{ request.POST.txtNumBins }}

See the template docs on variables for more info.

like image 34
Alasdair Avatar answered Oct 28 '25 11:10

Alasdair