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

问题描述 投票:1回答:1

我正在使用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.朋友

from django.forms import ModelForm
from .models import myModel


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

迷信.朋友

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.朋友

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

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

python ajax django python-3.x django-forms
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.