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?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With