Converting GET Actions to POST

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.

Pub Tech developer for Birkbeck CTP