[Answered ]-CSRF verification failed in django

1👍

As @Selcuk suggested, using the Django decorator csrf_exempt on your view function should fix this. However, take into consideration that it won’t protect your request against CSRF attacks.
You can read more about how it works here.

# Import django modules
from django.http import HttpResponse
# import csrf_exempt
from django.views.decorators.csrf import csrf_exempt
# Import system modules
import simplejson
# Import custom modules
from googlemaps.waypoints.models import Waypoint

@csrf_exempt 
def save(request):
    'Save waypoints'
    for waypointString in request.POST.get('waypointsPayload', '').splitlines():
        waypointID, waypointX, waypointY = waypointString.split()
        waypoint = Waypoint.objects.get(id=int(waypointID))
        waypoint.geometry.set_x(float(waypointX))
        waypoint.geometry.set_y(float(waypointY))
        waypoint.save()
    return HttpResponse(simplejson.dumps(dict(isOk=1)), mimetype='application/json')
👤Forge

1👍

The correct way to solve this is to add a {% csrf_token %} to your Django template. You need a form tag for this to work, and you should have one no matter what. Otherwise, how does the browser know where to send your data?

<form action="" method="post">
    {% csrf_token %}
    <input id=saveWaypoints type=button value=Save disabled=disabled>
</form

The Django documentation has lots of good information on how CSRF works and why it’s important:
https://docs.djangoproject.com/en/1.9/ref/csrf/#how-to-use-it

Leave a comment