fixes
[wolnelektury.git] / src / funding / widgets.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from decimal import Decimal, DecimalException
5 from django import forms
6 from django.template.loader import render_to_string
7
8
9 class PerksAmountWidget(forms.Textarea):
10     @staticmethod
11     def perks_input_name(name):
12         return "_%s_perk" % name
13
14     def render(self, name, value, attrs=None, renderer=None):
15         try:
16             value = Decimal(value)
17         except DecimalException:
18             pass
19         perks = list(self.form_instance.offer.get_perks())
20         perk_chosen = False
21         for perk in perks:
22             if perk.price == value:
23                 perk.chosen = True
24                 perk_chosen = True
25                 break
26
27         return render_to_string("funding/widgets/amount.html", {
28                 "perks": perks,
29                 "name": name,
30                 "perks_input_name": self.perks_input_name(name),
31                 "perk_chosen": perk_chosen,
32                 "value": value,
33                 "attrs": attrs,
34             })
35
36     def value_from_datadict(self, data, files, name):
37         num_str = data.get(self.perks_input_name(name)) or data[name]
38         return num_str.replace(',', '.')