[英]Django: how can I save objects to the database using FormView and ajax?
I am building an application using google maps api
where users can add and save markers on the map. 我正在使用
google maps api
构建应用程序,用户可以在其中添加和保存地图上的标记。 I am using ajax to send the form containing marker attributes to the backend. 我正在使用ajax将包含标记属性的表单发送到后端。 I am using
django's
heleper FormView
: 我正在使用
django's
heleper FormView
:
ajax.js: 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 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 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: 如您所见,我在这里建议将
form.save()
添加到form_valid
方法:
I also tried using UpdateView
instead as suggested here: 我还尝试按照这里的建议使用
UpdateView
:
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.
我想念什么。
Are you passing a CSRF token with the AJAX request ? 您是否要通过AJAX请求传递CSRF令牌 ? If not that could be why your form is invalid.
如果不是,那可能就是您的表格无效的原因。
This post explains how to include CSRF token in AJAX post . 这篇文章解释了如何在AJAX帖子中包含CSRF令牌 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.