Unverified Commit 33b00692 authored by David Haynes's avatar David Haynes
Browse files

Check if the form is valid before trying to make a URL

- this will allow us to display form errors before calling the post method
- keep things nice and abstracted
parent 9d3dca33
Pipeline #960 passed with stage
in 1 minute and 16 seconds
......@@ -47,7 +47,32 @@ def index(request):
# If a POST request is received, then the user has submitted a form and it's
# time to parse the form and create a new URL object
if request.method == 'POST':
return redirect('view', post(request).short)
# Now we initialize the form again but this time we have the POST
# request
url_form = URLForm(request.POST, host = request.META.get('HTTP_HOST'))
# Django will check the form to make sure it's valid
if url_form.is_valid():
# Call our post method to assemble our new URL object
res = post(request, url_form)
# If there is a 500 error returned, handle it
if res == 500:
return HttpResponseServerError(
render(request, 'admin/500.html', {})
)
# Redirect to the shiny new URL
return redirect('view', res.short)
# Else, there is an error, redisplay the form with the validation errors
else:
# Render index.html passing the form to the template
return render(request, 'core/index.html', {
'form': url_form,
},
)
# Render index.html passing the form to the template
return render(request, 'core/index.html', {
......@@ -58,14 +83,7 @@ def index(request):
#rate limits are completely arbitrary
@ratelimit(key='user', rate='3/m', method='POST', block=True)
@ratelimit(key='user', rate='25/d', method='POST', block=True)
def post(request):
# Now we initialize the form again but this time we have the POST
# request
url_form = URLForm(request.POST, host = request.META.get('HTTP_HOST'))
# Django will check the form to make sure it's valid
if url_form.is_valid():
def post(request, url_form):
# We don't commit the url object yet because we need to add its
# owner, and parse its date field.
url = url_form.save(commit = False)
......@@ -84,10 +102,9 @@ def post(request):
# one. However, if a random one can't be generated, return
# a 500 server error.
random_short = URL.generate_valid_short()
if random_short is None:
return HttpResponseServerError(
render(request, 'admin/500.html', {})
)
return 500
else:
url.short = random_short
......
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