I have a variable in django template who prints "Due 17 Dec, MATHS: math homework" I want only MATHS: math homework , how could I do that in django template.
To remove the initial character (per your question title),
{{ my_string|slice:':1' }}
But your example removes more than that
{{ my_string|slice:':12' }}
If the processing is more complex than that, do it in the view, or write your own custom template filter.
Django deliberately discourages significant processing in templates.
Related
Given text. Is there a django template tag to do:
text = 'hello there'
text[:3] ==> 'hel'
text[-3:] ==> 'ere'
Something like:
{{ text|left:3 }}
If not I can build a template tag for it but was wondering if it's already provided.
For a standard django template, you can use the slice template tag:
{{ text|slice:":3" }}
will only display the first three characters and
{{ text|slice:"-3:" }}
will only display the last three characters.
Essentially this template tag works just like the standard python slice syntax and just like standard slicing, it will work on both lists and strings. The docs only describe its use on lists so I can see why you'd be confused about this. Hope this helps!
https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#slice
I want to achieve something like this within a Django template.
{{ variable.function(parameter) }}
Where variable is a variable passed through a context to a template, in this case, an instance of a model.
I have tried different methods, but no one seems to work.
This is not possible in Django templates: they are crippled on purpose in order to prevent template designers from shooting themselves in the foot. The reasoning is that the only logic in templates should be presentation logic and all business logic should be kept in the view. Some people thinks it is fair enough and some think it is a bit condescending (those dumb template designers are not smart enough to use functions and methods safely).
I can think of 3 choices:
use jinja2 instead.
write a custom template filter.
keep all the logic in the view where Django designers think you are supposed to keep it.
I will not explain how to use Jinja2 because it is already explained in the docs and because the example in the question works verbatim if you switch to it instead of native Django templates. This simply works in Jinja2:
{{ variable.function(parameter) }}
Now the template filter solution: first you must follow a code layout convention. The filter itself would be something like this:
# at your_tag_library.py
#register.filter(name='call_with')
def apply_callable(callable, arg):
return callable(arg)
Then in the template you can do:
{% load your_tag_library %}
{{ variable.function|call_with:parameter }}
Of course the last option is the one from Daniel's answer - precompute the value in the view and just display the result in the template:
context['result'] = variable.function(parameter)
And in your template you just need {{ result }}.
There is no way to do this.
You can create another variable and pass it through the context so you could use it.
Like:
context['result'] = variable.function(parameter)
In your view.
And in your template:
{{ result }}
Imagine the context variable {{ url }} outputs www.example.com/<uuid-string> where <uuid-string> is different every time, whereas the former part of the URL stays the same.
Can one change the output of {{ url }} to instead www.forexample.com/<uuid-string>, via solely manipulating the string in the template and without involving views.py (which I know is the better way to do it, but that's not the question).
An illustrative example would be great.
read about filters and templatetags - they are a methods that allows you to perform some actions on variables in templates.
You can also create your own tags and filters that allow you to perform action non-built into Django template language
Simple example of such filter:
#in templatetags.py
#register.filter(name='duplicate')
def duplicate(value):
return value*2
#in your template
<p> {{ url|duplicate }} </p>
You can find more examples here. Also there you will find tutorial how to use and create them
I use |length filter in my templates to display the recordcount of my objects, however I'm currently forced to use .count since it seems that using the filter against a related set doesn't work! The following
{{ myobject.retatedObject_set.all|length }}
prints literally:
{{ myobject.retatedObject_set.all|length }}
And this:
{{ myobject.retatedObject_set.all.count }}
returns the expected result...
BUT: count() generates an extra SQL query, which is why I always use |length filter which doesn't! (see my answer: https://stackoverflow.com/a/18578147/267719 to question django - show the length of a queryset in a view)
Can this be considered a bug in the Django template engine? How can I avoid the extra query?
EDIT:
After an hard debug I realized that the problem was the use of the django-debug-toolbar (which prints in its panels each filter used as normal strings) plus the use of AngularJS (which has the same syntax for its templates). I solved by reconfiguring AngularJS to use different symbols:
config(function($interpolateProvider) {
$interpolateProvider.startSymbol('{$');
$interpolateProvider.endSymbol('$}');
});
I am using Django's humanize to make large float numbers in my app more readable. Also my app is available in different languages, and different languages use , and . signs in numbers the other way around.
For integer values the humanize tag intcomma works well:
{{ intvalue|intcomma }}
Would give for different locales:
English: 1,000,000
Dutch: 1.000.000
However, using floats this doesn't work very well. For example in my template you would find this:
{{ floatvalue|floatformat:2|intcomma }}
Would give for different locales:
English: 1,000,000.00
Dutch: 1,000,000,00
Note that instead of 1.000.000,00 for Dutch, it shows 1,000,000,00. Switching around the floatformat:2 and intcomma tags doesn't work either as then the value is nothing.
Any ideas on how to easily fix this?
(If possible, I'd rather not use an external libraries such as Babel)
Try the Django Format Localization feature. It gives you three options. As the Django docs say,
Django’s formatting system is capable to display dates, times and numbers in templates using the format specified for the current locale. It also handles localized input in forms.
When it’s enabled, two users accessing the same content may see dates, times and numbers formatted in different ways, depending on the formats for their current locale.
The formatting system is disabled by default. To enable it, it’s necessary to set USE_L10N = True in your settings file.
Thus this first option turns on locale-dependent number formatting for all of your templates.
A second option is to use the localize template tag to turn on locale-dependent number formatting for only part of a template. For example,
{% load l10n %}
{% localize on %}
{{ value }}
{% endlocalize %}
A third option is to use the localize template filter to force locale-dependent number formatting for a single value. For example,
{% load l10n %}
{{ value|localize }}