Django:如何使用FormView和ajax将对象保存到数据库?

时间:2018-03-02 18:47:43

标签: python ajax django python-3.x django-forms

我正在使用google maps api构建应用程序,用户可以在地图上添加和保存标记。我使用ajax将包含标记属性的表单发送到后端。我正在使用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 = '/'

但是在提交表单后,对象不会保存在数据库中。 正如您所看到的,我按照此处的建议将form.save()添加到form_valid方法:

  

Django FormView Not Saving

我也尝试使用UpdateView,而不是按照此处的建议:

  

Django. Simple FormView not saving

并尝试了其他解决方案但其中没有一个有效。 所以请帮帮我。我的代码中的问题在哪里?我错过了什么。

1 个答案:

答案 0 :(得分:0)

你是passing a CSRF token with the AJAX request吗?如果不是这可能是您的表单无效的原因。

这篇文章解释了如何include CSRF token in AJAX post