这是ajax操作和django视图之间的通信。
我有一个表单,如果我单击表单的“提交”按钮,则将执行Ajax代码。
Ajax代码:
function makeEvent(event){
event.preventDefault();
var year = event.target.childNodes[3].children[0].value.slice(0,4);
var month = event.target.childNodes[3].children[0].value.slice(5,7);
var day = event.target.childNodes[3].children[0].value.slice(8,10);
$.ajax({
type: "POST",
url: "{% url 'makeevent' %}",
data: {'form': $("#makeEventForm").serialize(), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response){
console.log(response);
refreshCalendarAjax(year, month);
listevent(year, month, day);
document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." );
},
error: function(request,status,error){
if (status == 599) {
$("#sidebar").html = error;
} else {
console.log(error);
}
},
});
}
查看代码:
def makeevent(request):
if request.method == "POST":
form = EventForm(request.POST.get('form', None))
if form.is_valid():
form.save()
return HttpResponse("Successful", status=200)
else:
return HttpResponse(form.errors, status=599)
else:
print("NOT POST");
如果我尝试通过表单提交数据,则会出现500错误,错误消息是:
Internal Server Error: /makeevent
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/workspace/CalendarProject/cencal/views.py", line 42, in makeevent
if form.is_valid():
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 185, in is_valid
return self.is_bound and not self.errors
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 180, in errors
self.full_clean()
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 381, in full_clean
self._clean_fields()
File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 393, in _clean_fields
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "/usr/local/lib/python3.7/site-packages/django/forms/widgets.py", line 258, in value_from_datadict
return data.get(name)
AttributeError: 'str' object has no attribute 'get'
我真的不知道为什么它不起作用:(感谢阅读
答案 0 :(得分:1)
表单数据在ajax请求中序列化。在初始化EventForm之前,必须使用django.http.QueryDict将其反序列化为视图函数中的dict。