forms.py 1.78 KB
Newer Older
Skia's avatar
Skia committed
1
2
3
4
5
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django import forms
from django.contrib.auth import logout, login, authenticate
import logging

Skia's avatar
Skia committed
6
from .models import User, Page
Skia's avatar
Skia committed
7
8
9
10
11
12

class RegisteringForm(UserCreationForm):
    error_css_class = 'error'
    required_css_class = 'required'
    class Meta:
        model = User
Skia's avatar
Skia committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
        fields = ('first_name', 'last_name', 'email')

    def save(self, commit=True):
        user = super(RegisteringForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        user.generate_username()
        if commit:
            user.save()
        return user

class LoginForm(AuthenticationForm):
    def login(self):
        u = authenticate(username=self.request.POST['username'],
                         password=self.request.POST['password'])
        if u is not None:
            if u.is_active:
                login(self.request, u)
Skia's avatar
Skia committed
30
                logging.debug("Logging in "+str(u))
Skia's avatar
Skia committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
            else:
                raise forms.ValidationError(
                        self.error_messages['invalid_login'],
                        code='inactive',
                        params={'username': self.username_field.verbose_name},
                    )
        else:
            logging.debug("Login failed")
            raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )

Skia's avatar
Skia committed
45
46
47
48
49
50
51
52
53
54
55
class PageForm(forms.ModelForm):
    class Meta:
        model = Page
        fields = ['name', 'title', 'content', ]

    def save(self, commit=True):
        page = super(PageForm, self).save(commit=False)
        if commit:
            page.save()
        return page

Skia's avatar
Skia committed
56