How to Set a Variable in Django Template

As you may have figured by now, Django does not implement such a feature. That is, because the logic of setting the variable must go in the view, not in the template. But there are some rare cases when you actually need this.

The way you can solve this is by using a custom Django template tag.

To do this, you create a file called in your templatetags folder that contains the following code:

Then to use this in your template, you just do the following:

As you can see, you can put in your variables anything that you could normally get inside a Django template: a number, another context variable, a string, etc.

Hope it helps 😉