Tuesday 15 April 2014

python - Django: Getting single element from related manager -



python - Django: Getting single element from related manager -

i have app user can "vote" on "post". in ui (template) i'd indicate whether user has voted. require doing (which doesn't work). there legal way in template (without re-writing views)?

i'm trying users have voted on post. doesn't work or create sense really, can communicate i'm trying achieve:

{% if user in post.post_votes.all.the_user %}

relevant parts of model:

class post(models.model): content = models.textfield(blank=false) class vote(models.model): the_user = models.foreignkey(user, related_name="post_votes") the_post = models.foreignkey("post", related_name="post_votes")

thanks!

you need pass user queryset filter. there no way built-in template syntax. should create own.

# app.templatetags.app_tags django import template register = template.library() @register.filter def has_voted(user, post): homecoming post.votes.filter(the_user=user).exists() # template {% load app_tags %} {% if user|has_voted:post %} <b>already voted</b> {% endif %}

alternativly, can loop on queryset of votes that's not idea.

python django django-models django-templates django-views

No comments:

Post a Comment