forms.py 2.42 KB
Newer Older
1
from django import forms
2
from go.models import URL, RegisteredUser
3
from django.core.validators import RegexValidator  # MinLengthValidator, MinValueValidator
4
from django.core.exceptions import ValidationError
5
from captcha.fields import CaptchaField
6

7
8

class URLForm(forms.ModelForm):
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

    DAY = '1 Day'
    WEEK = '1 Week'
    MONTH = '1 Month'
    NEVER = 'Never'

    EXPIRATION_CHOICES = (
        (DAY, DAY),
        (WEEK, WEEK),
        (MONTH, MONTH),
        (NEVER, NEVER),
    )

    # Add a custom expiration choice field.
    expires = forms.ChoiceField(
24
25
26
27
28
        required=True,
        label='Expiration',
        choices=EXPIRATION_CHOICES,
        initial=NEVER,
        widget=forms.RadioSelect(),
29
30
    )

31
    def unique_short(value):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
32
33
34
35
36
37
        try:
            URL.objects.get(short__iexact=value)
        except URL.DoesNotExist:
            return
        raise ValidationError('Short url already exists.')

Jean Michel Rouly's avatar
Jean Michel Rouly committed
38
    # Custom short-url field with validators.
39
    short = forms.SlugField(
40
41
42
        required=False,
        label='Short URL (Optional)',
        widget=forms.TextInput(attrs={}),
43
        validators=[unique_short],
44
45
        max_length=20,
        min_length=3,
46
47
48
49
    )

    class Meta:
        model = URL
50
51
        fields = ('target',)
        exclude = ('owner', 'short', 'date_created', 'clicks', 'expires')
52
53
54
55
        labels = {
            'target': 'Long URL',
        }
        widgets = {
56
            'target': forms.URLInput(attrs={
57
58
59
                'placeholder': 'http://',
            }),
        }
60
61


62
class SignupForm(forms.ModelForm):
63
64
65
66
67
68
69
70

    def validate_username(username):
        try:
            registered = RegisteredUser.objects.get(username=username)
            raise ValidationError('Username "%s" is already in use.' % username)
        except RegisteredUser.DoesNotExist:
            return

71
    username = forms.CharField(
72
73
74
        required=True,
        label='Mason NetID',
        max_length=30,
75
        validators=[validate_username],
76
        widget=forms.TextInput(attrs={
77
78
79
        }),
    )
    full_name = forms.CharField(
80
81
82
83
        required=True,
        label='Full Name',
        max_length=100,
        widget=forms.TextInput(attrs={
84
85
86
        }),
    )
    description = forms.CharField(
87
88
89
90
        required=False,
        label='Description (Optional)',
        max_length=200,
        widget=forms.Textarea(attrs={
91
92
        }),
    )
93
    captcha = CaptchaField()
94
95
96

    class Meta:
        model = RegisteredUser
97
        fields = '__all__'