|
@@ -12,52 +12,19 @@ register = template.Library()
|
12
|
12
|
QNT_SINGLE, QNT_MULTIPLE = 'single', 'multiple'
|
13
|
13
|
|
14
|
14
|
|
15
|
|
-@register.tag(name="basket_form")
|
16
|
|
-def do_basket_form(parse, token):
|
17
|
|
- """
|
18
|
|
- Template tag for adding the add-to-basket form to the
|
19
|
|
- template context so it can be rendered.
|
20
|
|
- """
|
21
|
|
- tokens = token.split_contents()
|
22
|
|
- if len(tokens) < 4 or tokens[3] != 'as':
|
23
|
|
- raise template.TemplateSyntaxError(
|
24
|
|
- "%r tag uses the following syntax: "
|
25
|
|
- "{%% basket_form request product_var as "
|
26
|
|
- "form_var %%}" % tokens[0])
|
27
|
|
-
|
28
|
|
- request_var, product_var, form_var = tokens[1], tokens[2], tokens[4]
|
29
|
|
-
|
30
|
|
- quantity_type = tokens[5] if len(tokens) == 6 else QNT_MULTIPLE
|
31
|
|
- if quantity_type not in (QNT_SINGLE, QNT_MULTIPLE):
|
32
|
|
- raise template.TemplateSyntaxError(
|
33
|
|
- "%r tag only accepts the following quantity types: "
|
34
|
|
- "'single', 'multiple'" % tokens[0])
|
35
|
|
- return BasketFormNode(request_var, product_var, form_var, quantity_type)
|
36
|
|
-
|
37
|
|
-
|
38
|
|
-class BasketFormNode(template.Node):
|
39
|
|
- def __init__(self, request_var, product_var, form_var, quantity_type):
|
40
|
|
- self.request_var = template.Variable(request_var)
|
41
|
|
- self.product_var = template.Variable(product_var)
|
42
|
|
- self.form_var = form_var
|
43
|
|
- self.form_class = (AddToBasketForm if quantity_type == QNT_MULTIPLE
|
44
|
|
- else SimpleAddToBasketForm)
|
45
|
|
-
|
46
|
|
- def render(self, context):
|
47
|
|
- try:
|
48
|
|
- request = self.request_var.resolve(context)
|
49
|
|
- product = self.product_var.resolve(context)
|
50
|
|
- except template.VariableDoesNotExist:
|
51
|
|
- return ''
|
52
|
|
-
|
53
|
|
- if not isinstance(product, Product):
|
54
|
|
- return ''
|
55
|
|
-
|
56
|
|
- initial = {}
|
57
|
|
- if not product.is_group:
|
58
|
|
- initial['product_id'] = product.id
|
59
|
|
- form = self.form_class(
|
60
|
|
- request.basket, product=product,
|
61
|
|
- initial=initial)
|
62
|
|
- context[self.form_var] = form
|
|
15
|
+@register.assignment_tag()
|
|
16
|
+def basket_form(request, product, quantity_type='single'):
|
|
17
|
+ if not isinstance(product, Product):
|
63
|
18
|
return ''
|
|
19
|
+
|
|
20
|
+ initial = {}
|
|
21
|
+ if not product.is_group:
|
|
22
|
+ initial['product_id'] = product.id
|
|
23
|
+
|
|
24
|
+ form_class = AddToBasketForm
|
|
25
|
+ if quantity_type == QNT_SINGLE:
|
|
26
|
+ form_class = SimpleAddToBasketForm
|
|
27
|
+
|
|
28
|
+ form = form_class(request.basket, product=product, initial=initial)
|
|
29
|
+
|
|
30
|
+ return form
|