其他分享
首页 > 其他分享> > 如何使用Django创建特定的if条件模板标签?

如何使用Django创建特定的if条件模板标签?

作者:互联网

我的问题是if条件.

我想这样的事情,但无法弄清楚如何做到这一点.

{% 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 %}

在收藏夹经理中,我创建了:

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

因为在Django模板中没有办法做到这一点,我可以做一个像这样的模板标签:

{% 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 %}

但怎么办呢?
你有更好的主意吗?

解决方法:

最简单的方法是创建一个过滤器.

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

并在模板中:

{% if restaurant|is_favourite_of:user %}

标签:python,django,django-templates,favorites
来源: https://codeday.me/bug/20190715/1464080.html