I getting no image path saved in database and no image saved in filesystem. Item istance is saved becaues image is not required. views.py
我没有保存在数据库中的图像路径,也没有保存在文件系统中的图像。保存项目金额,因为不需要图像。 views.py
def add_item(request, item_id):
if request.method == 'POST':
if request.is_ajax():
form = ItemForm(request.POST, request.FILES)
if form.is_valid():
user = request.user
title = form.cleaned_data['title']
content = form.cleaned_data['content']
image = form.cleaned_data['image']
item = Item.objects.get(id=item_id)
item.add_child(user=user, title=title, content=content, image=image) # add_child() because of using django-treebeard
return HttpResponse('')
else:
return HttpResponse('')
else:
return HttpResponse('')
jquery:
jQuery的:
$('#form_for_item').live('submit', function(){
var data = $("#form_for_item").serialize();
var url = '/something/add_item/' + $('#form_for_item').attr('name') + '/';
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(){
$('#my_form').children().remove();
}
});
return false;
});
I try also form image
give to my add_item(request, item_id)
function add this lines:
我也尝试将表单图像提供给我的add_item(request,item_id)函数添加以下行:
from django.core.files.uploadedfile import SimpleUploadedFile
image = SimpleUploadedFile(request.META['HTTP_X_FILE_NAME'],request.raw_post_data)
but didn't help.
How can I save image sent through ajax?
但没有帮助。如何保存通过ajax发送的图像?
1 个解决方案
#1
1
I think one of the issues may be that a normal jQuery AJAX request doesn't send the form data with content-type multipart/form-data
. Have a look at this question for more information on how to send form data via AJAX with jQuery.
我认为其中一个问题可能是普通的jQuery AJAX请求不会发送带有内容类型multipart / form-data的表单数据。有关如何使用jQuery通过AJAX发送表单数据的更多信息,请查看此问题。
This solution does not seem to be 100% cross-browser compatible. A workaround could be displaying the form in an iframe and then using jQuery to submit the form when it should be saved.
此解决方案似乎不是100%跨浏览器兼容。解决方法可能是在iframe中显示表单,然后使用jQuery在应该保存表单时提交表单。
#1
1
I think one of the issues may be that a normal jQuery AJAX request doesn't send the form data with content-type multipart/form-data
. Have a look at this question for more information on how to send form data via AJAX with jQuery.
我认为其中一个问题可能是普通的jQuery AJAX请求不会发送带有内容类型multipart / form-data的表单数据。有关如何使用jQuery通过AJAX发送表单数据的更多信息,请查看此问题。
This solution does not seem to be 100% cross-browser compatible. A workaround could be displaying the form in an iframe and then using jQuery to submit the form when it should be saved.
此解决方案似乎不是100%跨浏览器兼容。解决方法可能是在iframe中显示表单,然后使用jQuery在应该保存表单时提交表单。