加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:25:15 所属栏目:Python 来源:网络整理
导读:我的问题是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_
我的问题是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 %}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读