我的問題是如果條件。如何用Django創建特定的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模板沒有做它喜歡這種方式,我能做到這一點像一個templatetag:
{% 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 %}
但是怎麼做呢? 你有更好的主意嗎?
那好,我不知道,我們可以在一個if條件使用的過濾器。 – Natim 2009-10-10 15:16:09