开发者

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

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?


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

{% if entry in likes %}

Refer django docs


Go here. Very similar to what they're using on trunk. "Save this as smart_if.py in the templatetags folder of one of your apps. Then a simple {% load smart_if %} replaces the boring built-in Django {% if %} template with the new smart one."


If you're not running trunk one of the following should work:

Filter:

Replacement "if" tag, largely the basis for the new functionality in the upcoming 1.2 release:

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜