Update variable value inside template - django
I've seen enough examples that allow me to declare a new variable inside a template and set its value. But I want to update the value of a specific variable inside the template.
For example, I have a datetime field for an object and I want to add the timezone as per request.user
from the template. So I will create template filter
how {% add_timezone object.created %}
and what it will do is that it will add the timezone to object.created
, and after that when I access it {{object.created}}
, it will give me the updated value.
Can anyone tell me how this can be done. I know that I need to update the variable context
from the template filter. But I donβt know how.
source to share
You cannot change the value in the template, but you can define "scope" variables using the tag {% with %}
:
{% with created=object.created|add_timezone %}
Date created with fixed timezone: {{ created }}
{% endwith %}
where add_timezone
is a simple filter:
def add_timezone(value):
adjusted_tz = ...
return adjusted_tz
register.filter('add_timezone', add_timezone)
source to share