How to create a specific templatetag condition with Django?

My problem is the if condition.

I would like something like that, but I can’t figure out how to do it.

{% if restaurant.is_favorite_of(user) %}
     <img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" />
{% else %}
     <img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" />
{% endif %}

In the Favorites Manager, I created:

def is_favorite(self, user, content_object):
    """
    This method returns :
       - True if content_object is favorite of user
       - False if not
    >>> user = User.objects.get(username="alice")
    >>> fav_user = User.objects.get(username="bob")
    >>> fav1 = Favorite.create_favorite(user, fav_user)
    >>> Favorite.objects.is_favorite(user, fav_user)
    True
    >>> Favorite.objects.is_favorite(user, user)
    False
    >>> Favorite.objects.all().delete()

    Above if we test if bob is favorite of alice it is true.
    But alice is not favorite of alice.
    """
    ct = ContentType.objects.get_for_model(type(content_object))
    try:
        self.filter(user=user).filter(content_type = ct).get(object_id = content_object.id)
        return True
    except Favorite.DoesNotExist:
        return False

Since there is no way in Django's templates to make it like that, I could make a templatetag that would act like this:

{% is_favorite user resto %}
     <img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" />
{% else %}
     <img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" />
{% endif %}

But how to do that? Do you have an idea?

+3
source share
3 answers

The easiest way is to create a filter.

@register.filter
def is_favourite_of(object, user):
    return Favourite.objects.is_favourite(user, object)

and in the template:

{% if restaurant|is_favourite_of:user %}
+11
source

Perhaps I could use an inclusion tag .

Create a tag like this:

{% show_favorite_img user restaurant %}

templatetags / user_extra.py:

@register.inclusion_tag('users/favorites.html')
def show_favorite_img(user, restaurant):
    return {'is_favorite': Favorite.objects.is_favorite(user, restaurant)}
+2
source

, {% expr any%} , . , , ... , .

. http://www.djangosnippets.org/snippets/9/

0
source

Source: https://habr.com/ru/post/1719769/


All Articles