Django LogoIn a word, you can't.

Django was designed to keep the template system separate from the coding. This means that Django templates are mostly HTML with a bit of Django template code interspersed. This is very different from PHP where HTML and code are very tightly bound. Separating HTML development from application development allows specialists in those fields to work on the things they know best.

If you need to filter a query in a template, you have three options:

  1. Update a variable in a view.
    If the information is only going to be needed on time and in a particular view, it makes sense to make the information available in a variable that is passed to the template via the view. This is the easiest solution, but it doesn't make a lot of sense if you are going to be doing this in many views.
  2. Add a method to a model.
    If you want to make the results of a filtered query available in many views, and you don't need to pass parameter information from the template, then you can create a model method that provides that information.
    I like this method, but there is might be a reason it's not a good idea. Hopefully someone will add a comment and explain.
  3. Create a template tag.
    Creating a template tag is the most complicated solution. It provides the ability to pass information between the template and the application, and so it has a wide variety of uses. In the simple case where the query filter is static, this method makes the least sense.

I'm not a Django expert in any way. I've been involved in the development of one production Django application (AleTale). Django has become my development platform of choice, but I'm still learning its intricacies. If you have some thoughts on this post or Django in general, I encourage you to leave a comment or send me an email.