Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
SRCT
go
Commits
ee7c67c9
Commit
ee7c67c9
authored
Jan 31, 2014
by
Jean Michel Rouly
Browse files
Moved short input validation into the form class
parent
c8158785
Changes
2
Hide whitespace changes
Inline
Side-by-side
go/go/forms.py
View file @
ee7c67c9
...
...
@@ -32,23 +32,49 @@ class URLForm( forms.ModelForm ):
'Only letters are allowed.'
)
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
.
CharField
(
required
=
False
,
label
=
'Short URL (Optional)'
,
widget
=
forms
.
TextInput
(
attrs
=
{}),
validators
=
[
alphanumeric
,
unique_short
],
validators
=
[
alphanumeric
],
max_length
=
20
,
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
:
try
:
URL
.
objects
.
get
(
short__iexact
=
short
)
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.
else
:
short
=
URL
.
generate_valid_short
()
if
short
is
None
:
raise
ValidationError
(
'Unable to generate identifier. Try again.'
)
else
:
# 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
:
model
=
URL
fields
=
(
'target'
,)
...
...
go/go/views.py
View file @
ee7c67c9
...
...
@@ -87,13 +87,9 @@ def index(request):
url
.
owner
=
request
.
user
# If the user entered a short url, it's already been validated,
# so accept it. If they did not, however, then generate a
# random one and use that instead.
# so accept it.
short
=
url_form
.
cleaned_data
.
get
(
'short'
).
strip
()
if
len
(
short
)
>
0
:
url
.
short
=
short
else
:
url
.
short
=
URL
.
generate_valid_short
()
url
.
short
=
short
# Grab the expiration field value. It's currently an unsable
# string value, so we need to parse it into a datetime object
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment