I have the following Jinja code for my Django application:
<ul>
{% for key, value in course_avrg.items %}
<li>
{{ key }}: {{ value }}
</li>
{% endfor %}
</ul>
The course_ids is a dictionary with key course name (str) and value course id (int).
The course_avrg is another dictionary with key course name (str) and value course average (int)
In the above code, I'm trying to get the primary key value (int) of each course by passing the course name "key" into course_ids dictionary.
However, I get the following error:
Could not parse the remainder: '[key]' from 'course_ids[key]'
so how should I access dictionary value from within the Jinja URL tag?
You can write custom template filter:
#register.filter
def getvalue(dict, key):
return dict[key]
And use it in template like this:
{{ key }}: {{ value }}
Related
In a Django template, I want to construct dynamically urls
I try to concatenate (see below) but got an error :
Could not parse the remainder: '+key+'_index'' from ''ecrf:'+key+'_index''
{% for key, values in forms.items %}
<!-- for exemple a key would be 'inclusion' -->
{{ key|capfirst }}
{% endfor %}
urls
app_name='ecrf'
urlpatterns = [
path('inclusion/create/', views.InclusionCreate.as_view(), name='inclusion_create'),
expected result:
Inclusion
You can use the add template tag[Django docs] to add strings together:
{% for key, values in forms.items %}
<!-- for example a key would be 'inclusion' -->
{{ key|capfirst }}
{% endfor %}
But this feels a bit hacky to me, perhaps your forms dictionary can be restructured so that such logic is done in the view itself? For example the dictionary can be:
{'inclusion': {'value': <some_value>, 'create_url': 'ecrf:inclusion_create'}}
And in your template your loop would be:
{% for key, values in forms.items %}
<!-- for example a key would be 'inclusion' -->
{{ key|capfirst }}
{% endfor %}
How do I get key,value pair from object from get_object_or_404 in template, passed from view to template as context?
#views.py
def detail(request):
unknown = get_object_or_404(UnknownModel)
return render(request, 'app/display.html', { 'some_data':unknown })
and in app/display.html, I've been trying various approaches:
{{ some_data }}
{{ some_data.keys }}
{{ some_data.items }}
{% for key, value in some_data.items %}
{{ key }} - {{ value }}
{% endfor %}}
but none work.
If I knew the fields, I can access easily as below, but that's not the case
{{ some_data.field_1 }}
In your case unknown is instance of UnknownModel model.
In template, you are trying to iterate over this instance fields, but items method works
for dictionaries, not for your model. You can provide items method in your model to return dictionary with fields that you want or use following snippet:
{% for key, value in some_data.__dict__.items %}
{{ key }} - {{ value }}
{% endfor %}}
Method above will display many internal data related to your instance. Another (better) way of doing this is to convert your model instance to the dictionary inthe view and then pass it to the template. To achieve that, you can use django.forms.models.model_to_dict method.
from django.forms.models import model_to_dict
def detail(request):
unknown = get_object_or_404(UnknownModel)
return render(request, 'app/display.html', {'some_data':model_to_dict(unknown)})
I'm collecting data in multiple nested dicts and passing them to my template. I wrote a simple filter to get the data from the dict by key:
#register.filter
def get_item(dictionary, key):
return dictionary.get(key)
In my template I'm accessing the data:
{% for location_type_id, location_type_name in location_types.items %}
{% with disctrict=disctricts|get_item:location_type_id %}
...
{% endwith %}
{% endfor %}
When I'm using {{ debug }} I see:
{'districts': {5: {6: 'Friedrichshain'}, 7: {7: 'Kreuzberg', 8: 'Charlottenburg'}},
'location_types': {5: 'Bar', 7: '5'}}
But I get the error: 'str' object has no attribute 'get'. When printing the arguments of the filter I get an empty string passed to filter instead of a dict.
There's a typo in your template, which probably causes the error:
{% with disctrict=disctricts|get_item:location_type_id %} should be {% with disctrict=districts|get_item:location_type_id %}
You have a typo. The variable name is districts but you are using disctricts in the template.
How do I access the value of tuple through indexing in a template? When i try to do this....django gives me the error : Could not parse the remainder: '[0]' from 'tuple[0]'.
template.html:
{{ tuple[0] }}
views.py:
def fun(request):
tuple=('a','b','c','d')
return render(request,'template.html',{'tuple':tuple})
Simply access tuple as in code below:
{{ tuple.0 }}
Also consider using django built-in template tags to iterate over your data, see simple usage below:
{% for item in tuple %}
<span>
{{ item }}
</spam>
{% endfor %}
In a Django template, is there a way to get a value from a key that has a space in it?
Eg, if I have a dict like:
{"Restaurant Name": Foo}
How can I reference that value in my template? Pseudo-syntax might be:
{{ entry['Restaurant Name'] }}
There is no clean way to do this with the built-in tags. Trying to do something like:
{{ a.'Restaurant Name'}} or {{ a.Restaurant Name }}
will throw a parse error.
You could do a for loop through the dictionary (but it's ugly/inefficient):
{% for k, v in your_dict_passed_into_context %}
{% ifequal k "Restaurant Name" %}
{{ v }}
{% endifequal %}
{% endfor %}
A custom tag would probably be cleaner:
from django import template
register = template.Library()
#register.simple_tag
def dictKeyLookup(the_dict, key):
# Try to fetch from the dict, and if it's not found return an empty string.
return the_dict.get(key, '')
and use it in the template like so:
{% dictKeyLookup your_dict_passed_into_context "Restaurant Name" %}
Or maybe try to restructure your dict to have "easier to work with" keys.
You can use a custom filter as well.
from django import template
register = template.Library()
#register.filter
def get(mapping, key):
return mapping.get(key, '')
and within the template
{{ entry|get:"Restaurant Name" }}