1

I am building an application using google maps api where users can add and save markers on the map. I am using ajax to send the form containing marker attributes to the backend. I am using django's heleper FormView:

ajax.js:

$(document).on('submit', '.add_marker_form', function(event){

  event.preventDefault();

  // parse form attributes:
    // (irrelevent code here)

  $.ajax({
      method: 'POST',       // or 'type'
      url: '/map/saveMarker/',
      data: data,          // the four attributes
      csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()

      success: function(data){
      console.log("marker saved");
  },
      error: function(data){
      console.log("marker not saved");
   }
  });

 }) // document

forms.py

from django.forms import ModelForm
from .models import myModel


class SaveMarkerForm(ModelForm):
      class Meta:
          model = myModel
          fields = ['title', 'url', 'latitude', 'longitude']

mixin.py

from django.http import JsonResponse

  class AjaxFormMixin(object):

      def form_invalid(self, form):
          response = super(AjaxFormMixin, self).form_invalid(form)
          if self.request.is_ajax():
             return JsonResponse(form.errors, status=400)
          else:
            return response

      def form_valid(self, form):
          form.save()
          response = super(AjaxFormMixin, self).form_valid(form)
          if self.request.is_ajax():
             data = {
              'message': "Successfully submitted data."
             }
            return JsonResponse(data)
          else:
            return response

views.py

import requests
from django.views.generic.edit import FormView
from .forms import SaveMarkerForm
from .mixin import AjaxFormMixin


class SaveMarkerView(AjaxFormMixin, FormView):
      form_class = SaveMarkerForm
      template_name = 'map.html'
      success_url = '/'

But after submitting the form, the objects are not saved in the database. As you can see I added form.save() to form_valid method as suggested here:

Django FormView Not Saving

I also tried using UpdateView instead as suggested here:

Django. Simple FormView not saving

and also tried other solutions but none of them worked. so please help me. where is the problem in my code? what am I missing.

Peyman Kheiri
  • 397
  • 6
  • 22
  • What response do you get? Note that your Ajax success callback doesn't actually check what's in the response, which could just as easily be the form errors from form_invalid. – Daniel Roseman Mar 02 '18 at 19:07
  • @DanielRoseman thanks for the answer. I added console.log('data') to success and now it prints my whole html file in the console?? I am really lost – Peyman Kheiri Mar 02 '18 at 20:22

1 Answers1

0

Are you passing a CSRF token with the AJAX request? If not that could be why your form is invalid.

This post explains how to include CSRF token in AJAX post.

bdoubleu
  • 5,568
  • 2
  • 20
  • 53
  • thanks for your answer. Yes I am sending it like this: `csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()`. I removed it from the code above because I wanted to shorten it. – Peyman Kheiri Mar 03 '18 at 16:19