forms.py 2.22 KB
Newer Older
1 2
from django import forms
from go.models import URL
3
from django.core.validators import MinLengthValidator, MinValueValidator, RegexValidator
4
from django.core.exceptions import ValidationError
5
from captcha.fields import CaptchaField
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

    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(
        required = True,
        label = 'Expiration',
        choices = EXPIRATION_CHOICES,
        initial = NEVER,
27 28 29
        widget = forms.RadioSelect(),
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
30
    # Short field must be only letters.
31 32 33 34
    alphanumeric = RegexValidator(
        r'^[a-zA-Z]*$',
        'Only letters are allowed.'
    )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
35

Jean Michel Rouly's avatar
Jean Michel Rouly committed
36 37 38 39 40 41 42
    def unique_short( value ):
        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
43
    # Custom short-url field with validators.
44 45 46 47
    short = forms.CharField(
        required = False,
        label = 'Short URL (Optional)',
        widget = forms.TextInput(attrs={}),
Jean Michel Rouly's avatar
Jean Michel Rouly committed
48
        validators = [alphanumeric,unique_short],
49 50
        max_length = 20,
        min_length = 3,
51 52 53 54
    )

    class Meta:
        model = URL
55 56
        fields = ('target',)
        exclude = ('owner', 'short', 'date_created', 'clicks', 'expires')
57 58 59 60
        labels = {
            'target': 'Long URL',
        }
        widgets = {
61
            'target': forms.URLInput(attrs={
62 63 64
                'placeholder': 'http://',
            }),
        }
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88


class SignupForm( forms.Form ):
    username = forms.CharField(
        required = True,
        label = 'Username',
        max_length = 30,
        widget = forms.TextInput(attrs={
        }),
    )
    full_name = forms.CharField(
        required = True,
        label = 'Full Name',
        max_length = 100,
        widget = forms.TextInput(attrs={
        }),
    )
    description = forms.CharField(
        required = False,
        label = 'Description (Optional)',
        max_length = 200,
        widget = forms.Textarea(attrs={
        }),
    )
89
    captcha = CaptchaField()