Converting GET Actions to POST

Andy Byers
1 min readFeb 7, 2017

I’m currently converting chunks of code that make data changes on GET requests to use POST within the Django environment and thought it might be useful to document how I did it here.

Here is a snippet of code using a GET request to change data using a query string to pass the id to be deleted.

# Link in the Template
<a href={% url 'a_url' %}?delete={{ item.pk }}>Delete Me!</a>
# Code in View
if 'delete' in request.GET:
item_pk = request.GET.get('delete')
item = get_object_or_404(models.Item, pk=item_pk)
item.delete()
return redirect(reverse('a_url'))

Converting this to use POST isn’t terribly difficult.

# We've got a button in a form now
<form method="POST">
{% csrf_token %}
<button type="submit" name="delete" value="delete">Delete Me!</button>
</form>
# Code in View
if 'delete' in request.POST:
item_pk = request.POST.get('delete')
item = get_object_or_404(models.Item, pk=item_pk)
item.delete()
return redirect(reverse('a_url'))

If you are adding a button for multiple items, make sure you put the form outside the loop otherwise you’ll just have a tonne of forms that do the same thing taking up memory on the DOM. The CSRF_TOKEN tag will now provide us with protection from Cross-Site Request Forgery attempts.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Andy Byers
Andy Byers

Written by Andy Byers

Pub Tech developer for Birkbeck CTP

No responses yet

Write a response