Reputation: 25
I have a custom template tag as following:
@register.simple_tag
def call_method(obj, method_name, *args):
"""
Usage
in shell
obj.votes.exists(user_id)
in template
{% call_method obj.votes 'exists' user.id %}
"""
method = getattr(obj, method_name)
return method(*args)
Then I can call it in the template (Class-based detail view) as following.
{% call_method object.votes 'exists' user.id %}
My question is how can use this template tag in If statement? For example, why I cannot use like:
{% if call_method object.votes 'exists' user.id %}
I am using django-vote [https://github.com/shanbay/django-vote][1]
My goal is to check whether a user already voted so that I can change the class of the vote button. Otherwise, I can already check it in view. And it works fine.
If it is not possible to use the simple tag with argument within If statement, could you please suggest a way to reach my goal?
Edit: I am adding view.
def vote(request, slug):
term = Term.objects.get(slug=slug)
if term.votes.exists(user_id=request.user.id):
term.votes.down(user_id=request.user.id)
else:
term.votes.up(user_id=request.user.id)
return HttpResponseRedirect(term.get_absolute_url())
and Model:
class Term(VoteModel, models.Model):
Upvotes: 0
Views: 1652
Reputation: 186
why not to pass the variable from view to template? for example inside of view context you can set your own context variable, for example:
class MyView(generic.DetailView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
obj = self.get_object()
is_user_voted_already = obj.votes.exists(user_id)
context.update({
'is_user_voted_already': is_user_voted_already
})
return context
and in template view you can check. Just like this:
{% if is_user_voted_already %}code here if user voted already{%else}code here user not voted already{%endif%}
Upvotes: 1