1

I have these models:

class Gallery(models.Model):
   HeadImage = models.ImageField(upload_to="gallery",blank=True,null=True)

class News(Gallery):
   Name=models.CharField(max_length=100) 
   #some other fields

U know that with this inheritance,News model has a gallery_ptr field,now I'm going to update this field using ajax:

$.ajax({
    url:'{% url DrHub.views.editNews dr.webSite,news.pk %}',
    type:'POST',
    data:{id_HeadImage:$('#id_HeadImage').val(),id_title:$('#id_title').val(),id_category:$('#id_category').val(),id_description:$('#id_description').val()},
})

in views.py I do this:

        gForm=GalleryForm(request.POST['id_HeadImage'], request.FILES,instance=newsInstance.gallery_ptr)
        if gForm.is_valid():
           gForm.save()
        else:
           raise Http404

But Image of Gallery won't be saved,while is_valid() is True!

any suggestion?

Asma Gheisari
  • 5,794
  • 9
  • 30
  • 51

2 Answers2

3

You can't simply upload files in ajax like this. Furthermore, I believe $('#id_HeadImage').val() contains only the file name .

Please ref How can I upload files asynchronously?

Community
  • 1
  • 1
okm
  • 23,575
  • 5
  • 83
  • 90
2

The form is valid, but you haven't actually handled the uploaded file (i.e. read and saved it). Have a look at the example in the django docs.

You're right, the model form should take care of the uploading for you. Have you seen this related question? Have you made sure your template declares the form like:

<form action="." method="POST" enctype="multipart/form-data">

i.e. with multipart/form-data

Community
  • 1
  • 1
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177