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

标签 python django django-templates favorites

我的问题是 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 创建特定的 if 条件模板标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1546816/

相关文章:

python - 对嵌套列表中每个索引点的浮点值求和

python - 如何将 BitString 转换为 ctypes 字节数组?

python - Django 没有接受新的更改

python - 如何防止漂白剂逃逸 > (blockquote) 标签在 Markdown 中使用

python - Django 管理员将上下文添加到index.html

django - 否定 Django 模板中的 bool 值

Python Tkinter 按钮没有出现?

python - 如何生成粉红噪声图像?

django - 分解一小段 HTML [django]

Django:如果用户之前输入过地址