forms.py 1.61 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

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

    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,
26 27 28
        widget = forms.RadioSelect(),
    )

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

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

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