forms.py 2.35 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
    # Custom target URL field
10
11
12
13
14
    target = forms.URLField(
        required=True,
        label='Long URL',
        max_length=1000,
        widget=forms.URLInput(attrs={
15
            'placeholder': 'https://'
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
        })
    )

    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,
    )

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

57
58
    class Meta:
        model = URL
59
60
        fields = ('target',)
        exclude = ('owner', 'short', 'date_created', 'clicks', 'expires')
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__'