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:
I also tried using UpdateView
instead as suggested here:
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.