58π
dj.name.replace('&', 'and')
You can not invoke method with arguments.You need to write a custom filter.
Official guide is here:
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
Ok, here is my example, say, in an app named βquestionsβ, I want to write a filter to_and
which replaces β&β to βandβ in a string.
In /project_name/questions/templatetags, create a blank __init__.py
, and to_and.py
which goes like:
from django import template
register = template.Library()
@register.filter
def to_and(value):
return value.replace("&","and")
In template , use:
{% load to_and %}
then you can enjoy:
{{ string|to_and }}
Note, the directory name templatetags
and file name to_and.py
can not be other names.
16π
More useful:
from django import template
register = template.Library()
@register.filter
def replace(value, arg):
"""
Replacing filter
Use `{{ "aaa"|replace:"a|b" }}`
"""
if len(arg.split('|')) != 2:
return value
what, to = arg.split('|')
return value.replace(what, to)
- [Django]-Django CSRF framework cannot be disabled and is breaking my site
- [Django]-How can I tell whether my Django application is running on development server or not?
- [Django]-How to resolve AssertionError: .accepted_renderer not set on Response in django and ajax
5π
The documentation says thus:
Because Django intentionally limits the amount of logic processing available in the template language, it is not possible to pass arguments to method calls accessed from within templates. Data should be calculated in views, then passed to templates for display.
You will have to edit dj.name
beforehand.
Edit: looks like Pythoner knows a better way: registering a custom filter. Upvote him π
- [Django]-Django Calendar Widget?
- [Django]-Django: How can I create a multiple select form?
- [Django]-What is the SQL ''LIKE" equivalent on Django ORM queries?