comparison sat_website/forms.py @ 57:bfa8009f0769

improve the subscription form
author souliane <souliane@mailoo.org>
date Thu, 14 May 2015 22:46:57 +0200
parents a1e457ac6871
children 0d20fb28c32e
comparison
equal deleted inserted replaced
56:01e9c646999f 57:bfa8009f0769
19 19
20 You should have received a copy of the GNU Affero General Public License 20 You should have received a copy of the GNU Affero General Public License
21 along with Foobar. If not, see <http://www.gnu.org/licenses/>. 21 along with Foobar. If not, see <http://www.gnu.org/licenses/>.
22 """ 22 """
23 23
24 from django.utils.translation import ugettext_lazy as _, string_concat, get_language 24 from django.utils.translation import ugettext_lazy as _, ugettext, string_concat, get_language
25 from django.utils.html import format_html 25 from django.utils.html import format_html
26 from django.core.mail import send_mail 26 from django.core.mail import send_mail
27 from django import forms 27 from django import forms
28 from django.conf import settings 28 from django.conf import settings
29 from collections import OrderedDict 29 from collections import OrderedDict
30 from email import email 30 from email import email
31 import utils 31 import utils
32 import re
32 33
33 34
34 ## Fields ## 35 ## Fields ##
35 36
36 37
81 82
82 83
83 class RegistrationForm(forms.Form): 84 class RegistrationForm(forms.Form):
84 85
85 section_1 = Section(label=_(u'Identity')) 86 section_1 = Section(label=_(u'Identity'))
86 name = CharField(label=_(u'Name')) 87 name = CharField(label=_(u'Given name'))
87 surname = CharField(label=_(u'Surname')) 88 surname = CharField(label=_(u'Family name'))
88 address = CharField(label=_(u'Address, postal code, municipality')) 89 address = CharField(label=_(u"Address, postal code, municipality"), widget=forms.Textarea(attrs={'rows': 3}))
89 90
90 section_2 = Section(label=_(u'Contacts')) 91 section_2 = Section(label=_(u'Contacts'))
91 email = EmailField(label=_(u'Email address')) 92 email = EmailField(label=_(u'Email address'))
92 email_confirmation = EmailField(label=_(u'Email address confirmation')) 93 email_confirmation = EmailField(label=_(u'Email address confirmation'))
93 jid = EmailField(required=False, label=_(u'Jabber ID (for example your SàT login)')) 94 jid = EmailField(required=False, label=_(u'Jabber ID (for example your SàT login)'))
98 section_3b = Section(label="") 99 section_3b = Section(label="")
99 payment_method = ChoiceField(choices=[(u"transfer", _(u"Bank transfer")), (u"card", _(u"Credit or debit card"))], 100 payment_method = ChoiceField(choices=[(u"transfer", _(u"Bank transfer")), (u"card", _(u"Credit or debit card"))],
100 help_text=_(u'Choose "Bank transfer" to proceed manually with the association\'s IBAN/BIC numbers. Choose "Credit or debit card" to pay via CB, Visa or Mastercard using a secure banking service. For both methods, we will first send you an email containing all the details.'), widget=forms.RadioSelect) 101 help_text=_(u'Choose "Bank transfer" to proceed manually with the association\'s IBAN/BIC numbers. Choose "Credit or debit card" to pay via CB, Visa or Mastercard using a secure banking service. For both methods, we will first send you an email containing all the details.'), widget=forms.RadioSelect)
101 102
102 section_5 = Section(label=_(u'Reference')) 103 section_5 = Section(label=_(u'Reference'))
103 ref = CharField(required=False, label=_(u"Reference"), placeholder=_(u"Adherent number in case of a renewal")) 104 reference = CharField(required=False, label=_(u"Reference"), placeholder=_(u"Adherent number in case of a renewal"))
104 105
105 section_6 = Section(label=_(u'Comment')) 106 section_6 = Section(label=_(u'Comment'))
106 comment = CharField(required=False, label=_(u"Comment"), placeholder="", widget=forms.Textarea(attrs={'rows': 3})) 107 comment = CharField(required=False, label=_(u"Comment"), placeholder="", widget=forms.Textarea(attrs={'rows': 3}))
108
109 newsletter = BooleanField(required=False, label=_(u'I would like to receive the newsletter.'))
107 110
108 def html_link(url, label): 111 def html_link(url, label):
109 return string_concat('<a target="#" href="', url, '">', label, '</a>') 112 return string_concat('<a target="#" href="', url, '">', label, '</a>')
110 113
111 agreement_label = [_(u"I read the "), 114 agreement_label = [_(u"I read the "),
139 msg = _(u"Passwords don't match.") 142 msg = _(u"Passwords don't match.")
140 self.add_error('email_confirmation', msg) 143 self.add_error('email_confirmation', msg)
141 144
142 145
143 def results(self, user_readable=True): 146 def results(self, user_readable=True):
144 """Get the results submitted by the user as a list of couple. Keep the 147 """Get the results submitted by the user as a list.
145 pertinent fields and filter out the inappropriate ones. 148
146 149 Keep the pertinent fields and filter out the inappropriate ones.
147 @param user_readable: set to True to prefer the field labels to their names 150 @param user_readable: (bool) set to True to prefer the field labels to their names
148 @return: list of couple (name, value) or (label, value) 151 @return: list of couple (name, value) or (label, value)
149 """ 152 """
150 if not self.is_valid(): 153 if not self.is_valid():
151 return '' 154 return None
152 results = [] 155 results = []
153 for field in self: 156 for field in self:
154 if isinstance(field.field, Section): 157 if isinstance(field.field, Section):
155 continue 158 continue
156 if field.name in ('email_confirmation', 'agreement_confirmation') or not field.value(): 159 if field.name in ('email_confirmation', 'agreement_confirmation') or not field.value():
157 continue 160 continue
158 if field.name == "payment_method" and self['subscription_amount'].value() == "0": 161 if field.name == "payment_method" and self['subscription_amount'].value() == "0":
159 continue 162 continue
160 value = field.value() 163 key = field.name
164 if isinstance(field.field, BooleanField) and user_readable:
165 value = ugettext(u"yes") if field.value() else ugettext(u"no")
166 else:
167 value = re.sub(r"[\n\r]+", ", ", unicode(field.value()))
161 if user_readable: 168 if user_readable:
169 if isinstance(field.field, BooleanField):
170 key = key.capitalize() # to get Newsletter instead of "Please add me..."
171 else:
172 key = field.label
162 if isinstance(field.field, ChoiceField): 173 if isinstance(field.field, ChoiceField):
163 value = field.field.choice_label(value) 174 value = field.field.choice_label(value)
164 results.append((field.label, value)) 175 results.append((key, value))
165 else:
166 results.append((field.name, value))
167 if user_readable: 176 if user_readable:
168 results.append((_(u'Language'), utils.get_language_name_local(get_language()))) 177 results.append((_(u'Language'), utils.get_language_name_local(get_language())))
169 else: 178 else:
170 results.append(('lang', get_language())) 179 results.append(('lang', get_language()))
171 return results 180 return results
172 181
182 def result_as_dict(self, user_readable=True):
183 """Get the results submitted by the user as an OrderedDict.
184
185 @param user_readable (bool): set to True to prefer the field labels to their names
186 @return: dict {name: value} or {label: value}
187 """
188 return {key: value for key, value in self.results(user_readable)}
189
173 def result_as_string(self, user_readable=True): 190 def result_as_string(self, user_readable=True):
174 """Get the result as a string to be sent for example via email. 191 """Get the result as a string to be sent for example via email.
175 192
176 @param user_readable: set to True to prefer the field labels to their names 193 @param user_readable (bool): set to True to prefer the field labels to their names
177 @return: list of couple (name, value) or (label, value) 194 @return: unicode
178 """ 195 """
179 return '\n'.join([name + ': ' + value for name, value in self.results(user_readable)]) 196 return '\n'.join([name + ': ' + value for name, value in self.results(user_readable)])
180 197
198 def prepareResultForUser(self):
199 """Get the email body to send to the subscriber.
200
201 @return: unicode
202 """
203 ref = self['reference'].value()
204 data = {'name': self['name'].value(),
205 'surname': self['surname'].value(),
206 'amount': self['subscription_amount'].value(),
207 'ref_info': '(ref. {ref})'.format(ref=ref) if ref else '',
208 'iban': settings.ASSO_IBAN,
209 'bic': settings.ASSO_BIC,
210 'result': self.result_as_string(True)
211 }
212
213 HEADER = ugettext(u"""Tank you, {name}!
214
215 We received your submission and we are happy to count you in the members of the association.
216
217 """)
218 PAYMENT = ugettext(u"""You chose to support Salut à Toi with a subscription of {amount} euros. Please complete your adhesion with a bank transfer to:
219
220 Payee: Salut à Toi
221 IBAN: {iban}
222 BIC: {bic}
223 Reason: subscription of {name} {surname} {ref_info}
224
225 Or, if you prefer, you can proceed with a credit or debit card:
226
227 https://www.apayer.fr/salut-a-toi
228
229 """)
230 FOOTER = ugettext(u"""Below a copy of the information we received:
231
232 {result}
233
234 If you have any question, feel free to contact us.
235
236 Association Salut à Toi
237 http://salut-a-toi.org""")
238
239 return (HEADER + (PAYMENT if int(data['amount']) > 0 else "") + FOOTER).format(**data)
240
241 def prepareResultForAdmin(self):
242 """Get the email body to send to the admins.
243
244 @return: unicode
245 """
246 data = {'name': self['name'].value(),
247 'result': self.result_as_string(False)
248 }
249
250 MSG = ugettext(u"""New subscription received!
251
252 {result}
253
254 An email has been automatically sent to {name}, no additional action is required from your side.""")
255
256 return MSG.format(**data)
257
181 def process_submitted_data(self): 258 def process_submitted_data(self):
259 """Send emails to the subscriber and the admins."""
182 if not self.is_valid(): 260 if not self.is_valid():
183 return 261 return
184 # send email to user 262 # send email to user
185 send_mail(_(u'Subscription to Salut à Toi'), self.result_as_string(True), settings.EMAIL_BACKEND, [self['email'].value()], fail_silently=False) 263 send_mail(_(u'Subscription to Salut à Toi'), self.prepareResultForUser(), settings.EMAIL_BACKEND, [self['email'].value()], fail_silently=False)
186 # send email to admins 264 # send email to admins
187 send_mail(_(u'Subscription to Salut à Toi'), self.result_as_string(False), settings.EMAIL_BACKEND, [email for name, email in settings.ADMINS], fail_silently=False) 265 send_mail(_(u'Subscription to Salut à Toi'), self.prepareResultForAdmin(), settings.EMAIL_BACKEND, [email for name, email in settings.ADMINS], fail_silently=False)