Skip to content

Instantly share code, notes, and snippets.

@ismaild
Created February 23, 2012 14:44
Show Gist options
  • Save ismaild/1893138 to your computer and use it in GitHub Desktop.
Save ismaild/1893138 to your computer and use it in GitHub Desktop.
get_products template tag for django >mezzanine > cartridge (Work in progress)
from django import template
from django.db.models import get_model
register = template.Library()
class ProductContentNode(template.Node):
def __init__(self, num, varname):
model = 'shop.Product'
self.num = int(num)
self.num_check = num*4
self.varname = varname
self.model = get_model(*model.split('.'))
def render(self, context):
mod = self.model._default_manager.all().order_by('-id')[:self.num_check]
special_list = []
latest_list = []
for prod in mod:
if prod.on_sale():
special_list.append(prod)
else:
latest_list.append(prod)
special_list = special_list[:self.num]
latest_list = latest_list[:self.num]
context[self.varname] = {'specials':special_list, 'latest': latest_list}
return ''
@register.tag()
def get_products(parser, token):
# Syntax
# {% get_products 4 as products %}
bits = token.contents.split()
if len(bits) !=4:
raise template.TemplateSyntaxError, "get_products tag takes exactly Four arguments"
if bits[2] != 'as':
raise template.TemplateSyntaxError, "Third argument to get_products tag must be 'as'"
return ProductContentNode(bits[1],bits[3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment