Template and static file in django
In this tutorial we will learn about the templating in django in details:
1.{% if request.user.is_authenticated %}
{% else %}
{% endif %}
{% if request.user.id is not None %}
{% else %}
{% endif %}
{% for obj in objects %}
{{forloop.counter}} #(1-index)
{{forloop.counter()}} # (0 -index)
{{forloop.revcounter}}
{{forloop.revcounter()}}
{{forloop.first}} # 1st True other False
{{forloop.last}} # last True other False
{{forloop.parentloop}}
{% empty %}
{% endfor %}
{% for key , value in data.items %}
{{key}}:{{values}}
{% endfor %}
2.{{variable_name | filter_name}}
{{context | truncatechar:500}}
{{context | truncateword:500}}
{{context | length <0 }}
{{context | length }}
{{context | upper }}
{{context | slice:'2' }}
{{context | upper | truncatechar:200 }}
{{context | default:"nothings" }}
{{context | capfirst }}
{{context | floatformate }} # only one decimal
{{context | floatformate:3 }}
{{context | floatformate:"0" }} # rounded automatically
{{context | floatformate:"-3"}}
{{product.averagereview | String formate:"2.f"}}
d=datetime.now()
{{d | date:"D d M Y"}}
{{d | date:"DATE_FORMATE"}}
3.{{block.super}}
4.{{product.0.name}}
5. # to load static file
{% load static %}
<img src={{user.image.url}} />
<img src="/media/{{user.image}} />
<a href="{{i.notefile.url}}" download> {{i.notefile}}} </a>
{% url "register" %}
{% url "delete" st.id %}
6.{% block title %} {% endblock title %}
{% extends 'base.html' %}
{% include 'navbar.html' %}
{% include 'navbar.html' with p="php" d="django" %}
{% include 'navbar.html' with p="php" d="django" only %} # only this value is passed to navbar.html
How to make custom template tags in django templating
You can follow mention steps below to createe the custom tags
1. At first make the folder 'templatetags" inside django app then make __init__.py file and one python file(say, my_filter.py) inside it
structure looks like these
--> ap_name
--> templatetags
--> __init__.py
--> my_filter.py
2. The you can mention write custom tages inside my_filter.py file like
from django import template
register = template.Library()
@register.filter('multiply')
def multiply(value, arg):
return value * arg
@register.filter(name='remove_special')
def remove_chars(value, arg):
print("arg",arg)
print("val",val)
for character in arg:
value=value.replace(character,"")
return value
@register.filter
def modify_name(value):
return value.title()
@register.filter
def modify_name_with_arg(value, operation=None):
if operation == "title":
return value.title()
else:
return value.lower()
3. Then when every you need this filter , you have to load it at first ,
{% load my_filter %} #only file name not extension
{{candidate.job_city remove_special:"[]'{}"}} # here []'{} as a args
{{ exp.unit_price |multiply:rate }}
{% load my_tags %}
<div>
{{user.first_name|modify_name}}
</div>
<div>
{{user.first_name|modify_name_with_arg:"title"}}
</div>