forms.py 2.41 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
    # Check to make sure the short url has not been used
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
    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,
    )

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

58
59
    class Meta:
        model = URL
60
61
        fields = ('target',)
        exclude = ('owner', 'short', 'date_created', 'clicks', 'expires')
62

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

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

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

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