Commit 0476774e authored by Jean Michel Rouly's avatar Jean Michel Rouly
Browse files


parent ee7c67c9
...@@ -32,49 +32,23 @@ class URLForm( forms.ModelForm ): ...@@ -32,49 +32,23 @@ class URLForm( forms.ModelForm ):
'Only letters are allowed.' 'Only letters are allowed.'
) )
def unique_short( value ):
except URL.DoesNotExist:
raise ValidationError('Short url already exists.')
# Custom short-url field with validators. # Custom short-url field with validators.
short = forms.CharField( short = forms.CharField(
required = False, required = False,
label = 'Short URL (Optional)', label = 'Short URL (Optional)',
widget = forms.TextInput(attrs={}), widget = forms.TextInput(attrs={}),
validators = [alphanumeric], validators = [alphanumeric,unique_short],
max_length = 20, max_length = 20,
min_length = 3, min_length = 3,
) )
def clean(self):
Override the default clean method to check if the entered short
exists, or if none is entered, to generate a new one.
cleaned_data = super(URLForm, self).clean()
short = cleaned_data.get('short').strip()
# If the user has entered a value for short, then verify that it's
# unique.
if len(short) > 0:
except URL.DoesNotExist:
return cleaned_data
raise ValidationError('Short URL already exists.')
# If the user did not enter a value for short, then attempt to
# generate a ranomd url. If a random URL cannot be generated in 100
# attempts, raise an error.
short = URL.generate_valid_short()
if short is None:
raise ValidationError('Unable to generate identifier. Try again.')
# Set the new, randomly generated short value
cleaned_data['short'] = short
return cleaned_data
# This should never happen.
raise ValidationError('Server error. Try again.')
class Meta: class Meta:
model = URL model = URL
fields = ('target',) fields = ('target',)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment