forms.py 1.34 KB
Newer Older
1 2
from django import forms
from go.models import URL
3
from django.core.validators import MinLengthValidator, MinValueValidator, RegexValidator
4

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

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

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

    # Custom short-url field with validators.
35 36 37 38 39 40 41
    short = forms.CharField(
        required = False,
        label = 'Short URL (Optional)',
        widget = forms.TextInput(attrs={}),
        validators = [alphanumeric],
        max_length = 20,
        min_length = 3,
42 43 44 45
    )

    class Meta:
        model = URL
46 47
        fields = ('target',)
        exclude = ('owner', 'short', 'date_created', 'clicks', 'expires')
48 49 50 51
        labels = {
            'target': 'Long URL',
        }
        widgets = {
52
            'target': forms.URLInput(attrs={
53 54 55
                'placeholder': 'http://',
            }),
        }