from django import forms from pyrosapp.models import PyrosUser, Country, UserLevel, ScientificProgram from django.contrib.auth.models import User class PyrosUserCreationForm(forms.ModelForm): ''' Form used at user creation. IMPORTANT : The user must not be able to choose his Country, Scientific Program(s), Quota, Priority, and User Level ''' email = forms.EmailField(label="Email", widget=forms.TextInput) password = forms.CharField(label='Password', widget=forms.PasswordInput) password_confirm = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) first_name = forms.CharField(label='First name') last_name = forms.CharField(label='Last name') class Meta: model = PyrosUser fields = ('tel', 'laboratory', 'address') # fields = ('user.email', 'user_password', 'user_first_name', 'user_last_name', 'tel', 'laboratory', 'address') def __init__(self, *args, **kwargs): super(PyrosUserCreationForm, self).__init__(*args, **kwargs) self.fields.move_to_end('tel', True) self.fields.move_to_end('laboratory', True) self.fields.move_to_end('address', True) for field in self.fields.values(): field.required = True field.widget.attrs['class'] = "form-control" def clean_password_confirm(self): ''' Checks if password and confirmation are equal ''' password = self.cleaned_data.get("password") password_confirmation = self.cleaned_data.get("password_confirm") if password and password_confirmation and password != password_confirmation: raise forms.ValidationError("Passwords don't match") return password_confirmation def clean_email(self): ''' Checks if the email already exists in DB ''' email = self.cleaned_data.get("email") if User.objects.filter(email=email).exists(): raise forms.ValidationError("Email address already taken") return email def save(self): ''' Creates a User and a PyrosUser in DB ''' user = User.objects.create_user(username=self.cleaned_data['email']) user.email = self.cleaned_data['email'] user.set_password(self.cleaned_data['password']) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() pyros_user = PyrosUser.objects.create(user=user, country=Country.objects.all()[0], user_level=UserLevel.objects.all()[0], tel=self.cleaned_data['tel'], laboratory=self.cleaned_data['laboratory'], address=self.cleaned_data['address']) return pyros_user