Nettoyage, 1ère passe…
[auf_paf.git] / paf / forms.py
CommitLineData
0ba28d89 1from django import forms
2from captcha.fields import CaptchaField
3from paf.models import Student
4from django.contrib.auth.models import User, Group
5from string import zfill
6
7class RegistrationForm(forms.Form):
8 NATIONALITY_CHOICES = (
9 ('KH', 'Cambodgienne'),
10 ('LA', 'Laotienne'),
11 ('AN', 'Vietnamienne'),
12 ('ZZ', 'Autre'),
13 )
14 GENDER_CHOICES = (
15 ('M', 'Male'),
16 ('F', 'Female'),
17 )
18 lastname = forms.CharField()
19 firstname= forms.CharField()
20 nationality = forms.ChoiceField(choices=NATIONALITY_CHOICES)
21 sex = forms.ChoiceField(choices=GENDER_CHOICES)
22 dob = forms.DateField(label='date of birth', input_formats=('%d/%m/%Y',), help_text='input date of the form dd/mm/yyyy')
23 tel = forms.CharField()
24 parent_tel = forms.CharField(required=False)
25 parent_address = forms.CharField(max_length=120)
26 email = forms.EmailField(required=False)
27 captcha = CaptchaField()
28 password = forms.CharField(widget=forms.PasswordInput)
29 confirm_password = forms.CharField(widget=forms.PasswordInput)
30
31 def clean_confirm_password(self):
32 if self.cleaned_data['password'] != self.cleaned_data['confirm_password']:
33 raise forms.ValidationError("Your confirm password is different from password!")
34
35 def save(self):
36 student = self.create_student()
37 self.create_user(student)
38 return student
39
40 def create_student(self):
41 cd = self.cleaned_data
42 student = Student(lastname=cd['lastname']
43 , firstname=cd['firstname']
44 , nationality=cd['nationality']
45 , sex=cd['sex']
46 , dob=cd['dob']
47 , email=cd['email']
48 , tel=cd['tel']
49 , parent_tel=cd['parent_tel']
50 , parent_address=cd['parent_address'])
51 student.identifier = self.calculate_identifier(student)
52 student.save()
53 return student
54
55 def calculate_identifier(self, student):
56 try:
57 last_identifier = Student.objects.filter(nationality=student.nationality).order_by('-identifier')[0].identifier
58 tmp = int(last_identifier[2:]) + 1
59 return last_identifier[:2] + zfill(tmp, len(last_identifier)-2)
60 except:
61 return student.nationality + '0000001'
62
63 def create_user(self, student):
64 cd = self.cleaned_data
65 user = User(username=student.identifier, is_staff=1, first_name='student')
66 user.set_password(cd['password'])
67 user.save()
68 group = self.get_student_group()
69 user.groups = [group]
70 user.save()
71 return user
72
73 def get_student_group(self):
74 try:
75 group = Group.objects.get(name='student')
76 except:
77 group = Group(name='student')
78 group.save()
79 return group