Last active
October 1, 2020 06:39
-
-
Save mesuutt/9503844 to your computer and use it in GitHub Desktop.
Useful django template tags and filters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
import json | |
from django import template | |
from django.utils.dateparse import parse_datetime | |
from django.utils.html import mark_safe | |
register = template.Library() | |
@register.filter | |
def get_range(value, start_from=0): | |
""" | |
Filter - returns a list containing range made from given value | |
Usage (in template): | |
<ul>{% for i in 3|get_range %} | |
<li>{{ i }}. Do something</li> | |
{% endfor %}</ul> | |
Results with the HTML: | |
<ul> | |
<li>0. Do something</li> | |
<li>1. Do something</li> | |
<li>2. Do something</li> | |
</ul> | |
Instead of 3 one may use the variable set in the views | |
""" | |
return range(start_from, value) | |
@register.filter | |
def toJSON(value): | |
return mark_safe(json.dumps(value)) | |
@register.filter | |
def addcss(field, arg): | |
""" | |
Add class to field in templates | |
{{ field|addcss:'my-class' }} | |
""" | |
return field.as_widget(attrs={'class': arg}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Nginx rewrite rule for versioning static files. | |
.... | |
location ~* \.[0-9]+\.(css|js)$ { | |
rewrite (.*?)\.[0-9]+\.(css|js)$ $1.$2 last; | |
access_log off; | |
expires 365d; | |
} | |
.... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
def parse_date(date_str): | |
"""Parse date from string by DATE_INPUT_FORMATS of current language""" | |
for item in get_format('DATE_INPUT_FORMATS'): | |
try: | |
return datetime.datetime.strptime(date_str, item).date() | |
except (ValueError, TypeError): | |
continue | |
return None | |
def parse_datetime(date_str): | |
"""Parse datetime from string by DATETIME_INPUT_FORMATS of current language""" | |
for item in get_format('DATETIME_INPUT_FORMATS'): | |
try: | |
return datetime.datetime.strptime(date_str, item) | |
except (ValueError, TypeError): | |
continue | |
return None | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment