Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible, in a django template, to check if an object is contained in a list

Tags:

django

I'm very new to django, about a week into it.

I'm making a site where users enter stuff, then other users can vote on whether they like the stuff or not. I know it's not so novel, but it's a good project to learn a bunch of tools.

I have a many-to-many table for storing who likes or dislikes what. Before I render the page, I pull out all the likes and dislikes for the current user, along with the stuff I'm going to show on the page.

When I render the page, I go through the list of stuff I'm going to show and print them out one at a time. I want to show the user which stuff they liked, and which they didn't.

So in my django template, I have an object called entry. I also have two lists of objects called likes and dislikes. Is there any way to determine if entry is a member of either list, inside my django template.

I think what I'm looking for is a filter where I can say something like

{% if entry|in:likes %}

or

{% if likes|contains:entry %}

I know I could add a method to my model and check for each entry individually, but that seems like it would be database intensive.

Is there a better way to think about this problem?

like image 823
AlexH Avatar asked Mar 11 '10 18:03

AlexH


People also ask

How do I perform query filtering in Django templates?

The easiest is to do the filtering, then pass the result to render_to_response . Or you could write a method in your model so that you can say {% for object in data. filtered_set %} . Finally, you could write your own template tag, although in this specific case I would advise against that.

What does Django template contains?

Being a web framework, Django needs a convenient way to generate HTML dynamically. The most common approach relies on templates. A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted.

What is Django template filter?

Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can't modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to one's own need.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.


1 Answers

If you're using latest django version, then it's just

{% if entry in likes %}

Refer django docs

like image 134
Dmitry Shevchenko Avatar answered Oct 11 '22 06:10

Dmitry Shevchenko