improved request validation
[myslice.git] / portal / forms.py
1 # -*- coding: utf-8 -*-
2 #
3 # portal/forms.py: forms for the portal application
4 # This file is part of the Manifold project.
5 #
6 # Authors:
7 #   Jordan AugĂ© <jordan.auge@lip6.fr>
8 #   Mohammed-Yasin Rahman <mohammed-yasin.rahman@lip6.fr>
9 # Copyright 2013, UPMC Sorbonne UniversitĂ©s / LIP6
10 #
11 # This program is free software; you can redistribute it and/or modify it under
12 # the terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 3, or (at your option) any later version.
14
15 # This program is distributed in the hope that it will be useful, but WITHOUT
16 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 # FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18 # details.
19
20 # You should have received a copy of the GNU General Public License along with
21 # this program; see the file COPYING.  If not, write to the Free Software
22 # Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23
24 from django import forms
25 from portal.models import PendingUser, PendingSlice
26 #from crispy_forms.helper import FormHelper
27 #from crispy_forms.layout import Submit
28 from django.utils.translation import ugettext_lazy as _
29
30 # DEPRECATED # class UserRegisterForm(forms.Form): # Not ModelForm
31 # DEPRECATED #     """
32 # DEPRECATED #     Form for registering a new user account.
33 # DEPRECATED #     
34 # DEPRECATED #     Validates that the requested username is not already in use, and
35 # DEPRECATED #     requires the password to be entered twice to catch typos.
36 # DEPRECATED #     
37 # DEPRECATED #     Subclasses should feel free to add any additional validation they
38 # DEPRECATED #     need, but should avoid defining a ``save()`` method -- the actual
39 # DEPRECATED #     saving of collected user data is delegated to the active
40 # DEPRECATED #     registration backend.
41 # DEPRECATED # 
42 # DEPRECATED #     """
43 # DEPRECATED #     required_css_class = 'required'
44 # DEPRECATED #     
45 # DEPRECATED #     first_name = forms.RegexField(regex=r'^[\w+\s.@+-]+$',
46 # DEPRECATED #                                  max_length=30,
47 # DEPRECATED #                                  label=_("First name"),
48 # DEPRECATED #                                  error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
49 # DEPRECATED #     last_name = forms.RegexField(regex=r'^[\w+\s.@+-]+$',
50 # DEPRECATED #                                  max_length=30,
51 # DEPRECATED #                                  label=_("Last name"),
52 # DEPRECATED #                                  error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
53 # DEPRECATED #     affiliation = forms.RegexField(regex=r'^[\w+\s.@+-]+$',
54 # DEPRECATED #                              max_length=30,
55 # DEPRECATED #                              label=_("Affiliation"),
56 # DEPRECATED #                              error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
57 # DEPRECATED # 
58 # DEPRECATED #     email = forms.EmailField(label=_("E-mail"))
59 # DEPRECATED #     password1 = forms.CharField(widget=forms.PasswordInput,
60 # DEPRECATED #                                 label=_("Password"))
61 # DEPRECATED #     password2 = forms.CharField(widget=forms.PasswordInput,
62 # DEPRECATED #                                 label=_("Password (again)"))
63 # DEPRECATED #     keypair    = forms.CharField( widget=forms.FileInput )
64 # DEPRECATED #    
65 # DEPRECATED #     #my_keypairs = forms.ChoiceField(widget = forms.Select(), 
66 # DEPRECATED #     #             choices = ([('1','generate'), ('2','upload')])) 
67 # DEPRECATED #     tos = forms.BooleanField(widget=forms.CheckboxInput,
68 # DEPRECATED #                              label=_(u'I have read and agree to the Terms of Service'),
69 # DEPRECATED #                              error_messages={'required': _("You must agree to the terms to register")})
70 # DEPRECATED # 
71 # DEPRECATED # #    def clean_username(self):
72 # DEPRECATED # #        """
73 # DEPRECATED # #        Validate that the username is alphanumeric and is not already
74 # DEPRECATED # #        in use.
75 # DEPRECATED # #        
76 # DEPRECATED # #        """
77 # DEPRECATED # #        existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
78 # DEPRECATED # #        if existing.exists():
79 # DEPRECATED # #            raise forms.ValidationError(_("A user with that username already exists."))
80 # DEPRECATED # #        else:
81 # DEPRECATED # #            return self.cleaned_data['username']
82 # DEPRECATED # 
83 # DEPRECATED #     def clean_email(self):
84 # DEPRECATED #         """
85 # DEPRECATED #         Validate that the supplied email address is unique for the
86 # DEPRECATED #         site.
87 # DEPRECATED #         
88 # DEPRECATED #         """
89 # DEPRECATED #         if PendingUser.objects.filter(email__iexact=self.cleaned_data['email']):
90 # DEPRECATED #             raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
91 # DEPRECATED #         return self.cleaned_data['email']
92 # DEPRECATED # 
93 # DEPRECATED #     def clean(self):
94 # DEPRECATED #         """
95 # DEPRECATED #         Verifiy that the values entered into the two password fields
96 # DEPRECATED #         match. Note that an error here will end up in
97 # DEPRECATED #         ``non_field_errors()`` because it doesn't apply to a single
98 # DEPRECATED #         field.
99 # DEPRECATED #         
100 # DEPRECATED #         """
101 # DEPRECATED #         if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
102 # DEPRECATED #             if self.cleaned_data['password1'] != self.cleaned_data['password2']:
103 # DEPRECATED #                 raise forms.ValidationError(_("The two password fields didn't match."))
104 # DEPRECATED #         return self.cleaned_data
105 # DEPRECATED # 
106 # DEPRECATED #    class Meta:
107 # DEPRECATED #        model = PendingUser
108 # DEPRECATED #
109 # DEPRECATED #class SliceRequestForm(forms.ModelForm):
110 # DEPRECATED #    slice_name = forms.CharField( widget=forms.TextInput )
111 # DEPRECATED #    class Meta:
112 # DEPRECATED #        model = PendingSlice
113 # DEPRECATED #
114 # DEPRECATED #class RegisterUserStep2Form(forms.ModelForm):
115 # DEPRECATED #    class Meta:
116 # DEPRECATED #        model = PendingUser
117
118 class ContactForm(forms.Form):
119     first_name = forms.CharField()
120     last_name = forms.CharField()
121     affiliation = forms.CharField()
122     subject = forms.CharField(max_length=100)
123     message = forms.CharField(widget=forms.Textarea)
124     email = forms.EmailField()
125     cc_myself = forms.BooleanField(required=False)
126
127 class SliceRequestForm(forms.Form):
128     slice_name = forms.CharField()
129     authority_hrn = forms.ChoiceField(choices=[(1, 'un')])
130     number_of_nodes  = forms.DecimalField()
131     type_of_nodes = forms.CharField()
132     purpose = forms.CharField(widget=forms.Textarea)
133     email = forms.EmailField()
134     cc_myself = forms.BooleanField(required=False)
135
136     def __init__(self, *args, **kwargs):
137         initial =  kwargs.get('initial', {})
138         authority_hrn = initial.get('authority_hrn', None)
139
140         # set just the initial value
141         # in the real form needs something like this {'authority_hrn':'a'}
142         # but in this case you want {'authority_hrn':('a', 'letter_a')}
143         if authority_hrn:
144             kwargs['initial']['authority_hrn'] = authority_hrn[0]
145
146         # create the form
147         super(SliceRequestForm, self).__init__(*args, **kwargs)
148
149         # self.fields only exist after, so a double validation is needed
150         if authority_hrn:# and authority_hrn[0] not in (c[0] for c in authority_hrn):
151             # XXX This does not work, the choicefield is not updated...
152             #self.fields['authority_hrn'].choices.extend(authority_hrn)
153             self.fields['authority_hrn'] = forms.ChoiceField( choices=authority_hrn)
154