I want to convert this code to something more inheritable to avoid coding. Consider that my code is simple and simple answer is need.
{{ entity.name }}
{{ entity.description }}
I want to convert to such code:
{% for attribute in attributes %}
{{ entity ??? }} == entity.get_attr(attribute)
{% end for %}
What is valid syntax for it?
The easiest example with filter:
# templatetags.ry
from django import template
register = template.Library()
#register.filter
def get_attr(object, name):
return getattr(object, name, '')
Your template:
{% load templatetags %}
{% for attribute in attributes %}
{{ entity|get_attr:attribute }}
{% end for %}
Related
Say I have a model:
class Mymodel(models.Model)
property = models.IntegerField()
Say I have a function:
def func():
instance = Mymodel.objects.order_by('?')[0]
instance2 = Mymodel.objects.order_by('?')[0]
plan = [instance, instance2]
return plan
I want to use a for loop to add together the integers in the 'property' of the model instance and then output the sum into one of my templates?
I have tried the add filter but the problem is the amount of instances it will be adding together are dynamic so I can't simply do myModel.0.property|add:myModel.1.property
Thanks in advance.
EDIT:
Found a work around to this:
In your template just use the |length filter along with an if statement:
{% if instancelist|length == 2 %}
{{ instancelist.0.property|add:instancelist.1.property }}
{% else %}
{{ instancelist.0.property|add:instancelist.1.property|add:instancelist.2.property }}
{% endif %}
And so on.
Found a work around to this:
In your template just use the |length filter along with an if statement:
{% if instancelist|length == 2 %}
{{ instancelist.0.property|add:instancelist.1.property }}
{% else %}
{{ instancelist.0.property|add:instancelist.1.property|add:instancelist.2.property }}
{% endif %}
I am passing two dictionaries to a Django template (reservations , prices) inside the template i have something like this:
{% for key,value in reservations.items %}
...
...
{% if value is False %}
<div class="room">
<p class="room-id">{{ prices.{{ key }} }}</p>
</div>
{% else %}
...
...
{% endfor %}
now the problem is this line {{ prices.{{ key }} }} i am trying to evaluate the key value from the reservations dict to be used in the
prices dict how this can be done? and thank you in advance.
Only with custom template tags, for example:
# access_tags.py
from django import template
register = template.Library()
#register.filter(name='access')
def access(value, arg):
return value.get(arg, value.get(unicode(arg), None))
and in template:
{% load access_tags %}
...
<p class="room-id">{{ prices|access:key }}</p>
...
(Django , Python) I have created a list of book objects and it is being passed as context in my views.py along with the current session. On my template, i was to check if the books in that list are stored in the session, and if they are i want to access some info relating to that book within that session. how do i access the books in the session dynamically? is there a way?
i know i can access them by using "request.session.name" (where "name" is the same of the space in the session it is stored)
There are several book titles saved in the session, the way they are saved are as follows (in a function under views.py)
request.session["random book title"] = "random dollar price"
i want to access that "random dollar price" dynamically in a template.
this is the block of code in the template
{% for book in book_list %}
{% if book.title in request.session %}
{{ request.session.??? }}
{% endif %}
{% endfor %}
Thank you in advance!
You can make a custom template tag to look up by attribute like here
Performing a getattr() style lookup in a django template:
# app/templatetags/getattribute.py
import re
from django import template
from django.conf import settings
numeric_test = re.compile("^\d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
elif numeric_test.match(str(arg)) and len(value) > int(arg):
return value[int(arg)]
else:
return settings.TEMPLATE_STRING_IF_INVALID
register.filter('getattribute', getattribute)
Now change your template to
{% load getattribute %}
{% for book in book_list %}
{% if book.title in request.session %}
{{ request.session|getattribute:book.title }}
{% endif %}
{% endfor %}
This is a basic custom template tag example:
Django - Simple custom template tag example
and docs:
https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/
From what I remember from my django days should work
You can put session data in a dictionary and send this data to target template when you want to render it in view function.
def some_function(request):
context={
'data':sessionData #put session data here
}
return render(request,"pass/to/template.html",context)
Now you can access 'data' in your template.html
I think you should just send a list of book names from your view instead of a queryset so when you are crosschecking with session you use the title directly instead.
{% for book in book_list %}
{% if book in request.session %}
{{ request.session.book }}
{% endif %}
{% endfor %}
I have the following Django template.
{% load custom_tags %}
<ul>
{% for key, value in value.items %}
<li> {{ key }}: {{ value }}</li>
{% endfor %}
I need to check for the value and do some modifications.
If the value is True , instead of value I have to print Applied , else if it False I need to print Not Applied.
How to achieve that?
Very simple if-else clause here. Take a look at the django template docs to familiarize yourself with some of the common tags.
{% if value %}
APPLIED
{% else %}
NOT APPLIED
{% endif %}
You asked how to do this as a filter... I'm not sure why, but here is it:
In your app's templatetags directory create a file called my_tags.py or something and make the contents
from django import template
register = template.Library()
#register.filter
def applied(value):
if value:
return 'Applied'
else:
return 'Not applied'
Then in your template make sure to have {% load my_tags %} and use the filter with {{ value|applied }}
I currently have this for loop inside my template:
{% for i in 1234|make_list %}
I would like to obtain something like this inside loop:
{{ form.answer_{{ i }} }}
I am aware that the above line is not valid (it raises TemplateSyntaxError), but I would like to know if there is any way to use the value of i as part my other variable name.
First, you would need a custom template filter to mimic getattr() functionality, see:
Performing a getattr() style lookup in a django template
Then, you would need add template filter for string concatenation:
{% load getattribute %}
{% for i in 1234|make_list %}
{% with "answer_"|add:i as answer %}
{{ form|getattribute:answer }}
{% endwith %}
{% endfor %}