forms.py 3.81 KB
Newer Older
1
2
from __future__ import unicode_literals

3
4
from django import forms
from django.contrib.auth.models import User
5
6
from django.contrib.auth.forms import UserChangeForm as BaseUserChangeForm
from django.contrib.auth.forms import UserCreationForm as BaseUserCreationForm
Thom Wiggers's avatar
Thom Wiggers committed
7
8
from django.template import loader
from django.utils import translation
9
from django.utils.translation import ugettext
10
from django.utils.translation import ugettext_lazy as _
11

12
from .models import Profile
13
14


15
class ProfileForm(forms.ModelForm):
16
17
18
19
    class Meta:
        fields = ['address_street', 'address_street2',
                  'address_postal_code', 'address_city', 'phone_number',
                  'emergency_contact', 'emergency_contact_phone_number',
20
                  'show_birthday', 'website',
21
22
23
                  'profile_description', 'nickname',
                  'display_name_preference', 'photo', 'language',
                  'receive_optin', 'receive_newsletter']
24
        model = Profile
25

26
    def clean(self):
27
28
        super().clean()
        errors = {}
29
30
31
        direct_debit_authorized = self.cleaned_data\
            .get('direct_debit_authorized')
        bank_account = self.cleaned_data.get('bank_account')
32
33
34
35
        if direct_debit_authorized and not bank_account:
            errors.update({'bank_account': _('Please enter a bank account')})

        raise forms.ValidationError(errors)
36

37

38
class UserCreationForm(BaseUserCreationForm):
39
40
41
    # Don't forget to edit the formset in admin.py!
    # This is a stupid quirk of the user admin.

42
43
44
45
46
    # shadow the password fields to prevent validation errors,
    #   since we generate the passwords dynamically.
    password1 = None
    password2 = None

47
48
49
50
51
52
53
54
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in ('email', 'first_name', 'last_name'):
            self.fields[field].required = True

    send_welcome_email = forms.BooleanField(
        label=_('Send welcome email'),
        help_text=_('This email will include the generated password'),
55
        required=False,
56
57
        initial=True)

58
    def clean(self):
59
60
61
        if 'username' in self.cleaned_data:
            self.cleaned_data['username'] = (self.cleaned_data['username']
                                             .lower())
62
63
        super().clean()

64
65
    def save(self, commit=True):
        password = User.objects.make_random_password(length=15)
66
67
        # pass the password on as if it was filled in, so that save() works
        self.cleaned_data['password1'] = password
68
69
70
71
72
        user = super().save(commit=False)
        user.set_password(password)
        if commit:
            user.save()
        if self.cleaned_data['send_welcome_email']:
73
            # Ugly way to get the language since member isn't available
74
            language = str(self.data.get('profile-0-language', 'en'))
75
76
77
            if language not in ('nl', 'en'):
                language = 'en'
            with translation.override(language):
Thom Wiggers's avatar
Thom Wiggers committed
78
                email_body = loader.render_to_string(
Thom Wiggers's avatar
Thom Wiggers committed
79
                    'members/email/welcome.txt',
80
81
82
83
84
                    {
                     'full_name': user.get_full_name(),
                     'username': user.username,
                     'password': password
                     })
85
                user.email_user(
86
                    ugettext('Welcome to Study Association Thalia'),
87
                    email_body)
88
89
90
91
92
93
94
        return user

    class Meta:
        fields = ('username',
                  'first_name',
                  'last_name',
                  'send_welcome_email')
95
96


97
class UserChangeForm(BaseUserChangeForm):
98
99
100
101
102

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def clean(self):
103
104
105
        if 'username' in self.cleaned_data:
            self.cleaned_data['username'] = (self.cleaned_data['username']
                                             .lower())
106
        super().clean()