views:

24

answers:

2

I have a user model, an item model, and a possession model to store data about a user possessing an item. When a user is logged in and viewing an item, I want to display an 'add to my items' button, unless the user already has the item.

I was trying this code in the template:

{% if not user.possession_set.filter(item=item.id) %}    
<input type='submit' value='add to my items' />
{% endif %}

where item is the foreign key name for the item object in my possession model and item.id is the primary key for the item being displayed to the user

but I get this error:

Could not parse the remainder: '(item=item.id)'

I'm thinking I can't use the .filter() function since that is for querying the database? I found django's template filters, like this one: http://docs.djangoproject.com/en/1.1/ref/templates/builtins/#get-digit but there aren't any that can be combined to filter for a certain value of item. It seems I would have all the information in the template to do this, since I'm getting the user and it's possession_set, which should have the item field for each possession, so I'm thinking it's just a syntax thing?

Thanks for the help!

+1  A: 

You can't use such complicated expressions in the template, only in the view. Compute the information, whether user can have this button in the view and pass a single True or False value to the template. For example:

in view

allow_addition = not user.possession_set.filter(item=item.id)

and in template:

{% if allow_addition %}
  <input type='submit' value='add to my items' />
{% endif %}
gruszczy
Yup! That should work. I was wondering what would be a good implementation if there were many items that you wanted to do this with? Makes it a bit harder.
Jordan Messina
A: 

You could write a custom template filter for this.

def owns(user, id):
    return not user.possession_set.filter(item=id)

Then, in your template:

{% load mystuff %}
{% if user|owns:item.id %}

Check the Django docs at http://docs.djangoproject.com/en/1.1/howto/custom-template-tags/ for more info. Not sure if passing item.id as the filter argument will work, though.

LeafStorm
awesome! it worked great! thanks!
gohnjanotis