forms.py 2.25 KB
Newer Older
1
from django import forms
2
from go.models import URL, RegisteredUser
3
from django.core.exceptions import ValidationError
4
from captcha.fields import CaptchaField
5

6
7

class URLForm(forms.ModelForm):
8

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    target = forms.URLField(
        required=True,
        label='Long URL',
        max_length=1000,
        widget=forms.URLInput(attrs={
            'placeholder': 'http://'
        })
    )

    def unique_short(value):
        try:
            URL.objects.get(short__iexact=value)
        except URL.DoesNotExist:
            return
        raise ValidationError('Short url already exists.')

    # Custom short-url field with validators.
    short = forms.SlugField(
        required=False,
        label='Short URL (Optional)',
        widget=forms.TextInput(),
        validators=[unique_short],
        max_length=20,
        min_length=3,
    )

35
36
37
38
39
40
41
42
43
44
45
46
47
48
    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(
49
50
51
52
53
        required=True,
        label='Expiration',
        choices=EXPIRATION_CHOICES,
        initial=NEVER,
        widget=forms.RadioSelect(),
54
55
    )

56
57
    class Meta:
        model = URL
58
        fields = '__all__'
59

60
class SignupForm(forms.ModelForm):
61
62
63
64
65
66
67
68

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

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

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