captnvitman
captnvitman

Reputation: 313

AJAX data being sent to the wrong Django view

I'm new to django and ajax so I've been working on a project to learn it. I have two buttons, one that adds a marker and one that deletes a marker.

Here is the views.py

@csrf_exempt
def save(request):
    searchVar = request.POST.getlist('search[]')
    waypoint = Waypoint()
    waypoint.name = searchVar[0]
    waypoint.geometry = ('POINT(' + searchVar[2] + " " + searchVar[1] + ')')
    waypoint.save()
    return HttpResponse(json.dumps(dict(isOk=1)), content_type='application/json')

@csrf_exempt
def remove(request):
    objectID = request.POST.get('id')
    point = get_object_or_404(Point, pk = objectID)
    point.delete()

Here is the urls.py

from django.conf.urls import patterns, url, include

urlpatterns = patterns('googlemaps.waypoints.views',
    url(r'^$', 'index', name='waypoints-index'),
    url(r'', 'save', name='waypoints-save'),
    url(r'', 'remove', name='waypoints-remove'),
)

and here is the ajax from the js file

    $('#saveWaypoints').click(function () {
    var searchList = [search.name, search.geometry.location.lat(), search.geometry.location.lng()]
    $.ajax({
      url : "waypoints-save",
      type : "POST",
      data : { search : searchList }
    }, function (data) {
        if (data.isOk) {
            $('#saveWaypoints');
        } else {
            alert(data.message);
        }
    });
});
$('#removeWaypoints').click(function () {
  console.log(markerID);
    $.ajax({
      url : "waypoints-remove",
      type : "POST",
      data : { id : markerID }
    }, function (data) {
        if (data.isOk) {
            $('#removeWaypoints');
        } else {
            alert(data.message);
        }
    });
});

The save button works fine, but when I click on the remove button I get this error in my console log

POST http://127.0.0.1:8000/waypoints-remove 500 (Internal Server Error)

IndexError at /waypoints-remove
list index out of range

Request Method: POST
Request URL: http://127.0.0.1:8000/waypoints-remove

and this error in my server cmd

Internal Server Error: /waypoints-remove
Traceback (most recent call last):
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\rnvitter\virtualenv4\googlemaps\googlemaps\waypoints\views.py", line 23, in save
    waypoint.name = searchVar[0]
IndexError: list index out of range
2017-01-09 22:40:11,781 - ERROR - Internal Server Error: /waypoints-remove
Traceback (most recent call last):
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\rnvitter\virtualenv4\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\rnvitter\virtualenv4\googlemaps\googlemaps\waypoints\views.py", line 23, in save
    waypoint.name = searchVar[0]
IndexError: list index out of range

Which leads me to believe that the data from the remove button ajax call is being sent to my save view, does anyone know one?

Upvotes: 1

Views: 611

Answers (2)

Dan Lowe
Dan Lowe

Reputation: 56518

You have defined two URL entries that have the same regex.

url(r'', 'save', name='waypoints-save'),
url(r'', 'remove', name='waypoints-remove'),

Since /waypoints-remove would match r'' (a regex with nothing in it, therefore it will match anything), the first match wins, and the save method is executed. So the method you expected to run, remove, is not being run.

Upvotes: 2

Phin Jensen
Phin Jensen

Reputation: 441

You have your urls.py file set up wrong. The first parameter is a regular expression to match a URL, so ^$ will match the root path. The name parameter is for getting the URL for a specific view, e.g. when you use the reverse function.

^ indicates the beginning of a line and $ indicates the end of a line. Together, with nothing in between, it will match an empty line.

To match another URL, such as /waypoints-save/, you would need to write another regex: ^/waypoints-save/$. This will match the beginning of the line, followed by the characters /waypoints-save/, followed by the end of the line. To get your entire urls.py set up correctly, it should look like this:

from django.conf.urls import patterns, url, include

urlpatterns = patterns('googlemaps.waypoints.views',
    url(r'^$', 'index', name='waypoints-index'),
    url(r'^/waypoints-save/$', 'save', name='waypoints-save'),
    url(r'^/waypoints-remove/$', 'remove', name='waypoints-remove'),
)

Upvotes: 3

Related Questions