Reputation: 6254
I'm going to edit an ImageField using jquery ajax,after searching I found out I should use jquery form plugin,so I think using introduced method in this article is good : http://www.laurentluce.com/posts/upload-to-django-with-progress-bar-using-ajax-and-jquery/ But I wanna get data of POST image and give it to a model form to handle It,because It take care of every thing,even when the name of file is repeated,some thing like this:
<form id='form_upload' action="." method="POST" enctype="multipart/form-data">
<input type='file' id='id_HeadImage' />
</form>
<script typr="text/javascript">
var options = {
dataType: 'xml',
url: '{% url DrHub.views.editNews param1,param2 %}',
beforeSubmit: showRequest,
success: showResponse
}
$('#form_upload').ajaxSubmit(options);
</script>
and in server side :
if ('id_HeadImage' in request.FILES) and (request.FILES['id_HeadImage']):
gForm=GalleryForm(request.FILES['id_HeadImage'],instance=newsInstance.gallery_ptr)
if gForm.is_valid():
gForm.save()
as U can see I'm going to edit ImageField of a model named Gallery
but this way I just get the file name.
How can I do this?
EDIT
this is Gallery Model:
class Gallery(models.Model):
HeadImage = models.ImageField(upload_to="gallery",blank=True,null=True)
EDIT
Request.FILES is empty and ajax just post file name,not data!
Upvotes: 0
Views: 372
Reputation: 33410
Set the name attribute of your file input
Instanciate the form with request.POST and request.FILES as such: gForm=GalleryForm(request.POST, request.FILES, instance=newsInstance.gallery_ptr)
Also this:
if ('id_HeadImage' in request.FILES) and (request.FILES['id_HeadImage']):
Could be more pythonic:
if 'id_HeadImage' in request.FILES.keys():
Upvotes: 1