Question

I am unable to upload file if there are multiple fields in my model other than file field. I didn't get any error on the page but the page simply displays same page without uploading of my image.

Here is my model

class ImageUpload(models.Model):
   username = models.ForeignKey(User)
   imagefile = models.FileField(upload_to='pictures')
   isapproved = models.BooleanField()
   class Meta:
       db_table = u'imageupload'

   def __unicode__(self):
       return u'%s' % (self.imagefile)

Here is my model form

class UploadImageForm(forms.ModelForm):
   def __init__(self,user, *args, **kwargs):
       super(UploadImageForm, self).__init__(*args, **kwargs)
       self.fields['username'] = forms.CharField(initial = user,
                                       widget = forms.TextInput(
                                     attrs = {'readonly':'readonly'}))
   class Meta:
       model = ImageUpload
       exclude = ('id', 'isapproved')

Here is my view where I am handling the data.

def imageupload(request):
# Handle file upload
   if request.method == 'POST':
      list = ["jpeg", "jpg","JPG","JPEG","png","PNG"]
      format = imghdr.what(request.FILES['imagefile'])
      if format not in list:
          error = "Please upload a valid file format"
          form = UploadImageForm(request.user)
          return HttpResponseRedirect(reverse('myview.views.imageupload'))
      else:
          form = UploadImageForm(request.POST, request.FILES)
          if form.is_valid():
              newdoc = ImageUpload(imagefile = request.FILES['imagefile'])
              newdoc.save()
          return HttpResponseRedirect(reverse('myview.views.imageupload'))
  else:
      form = UploadImageForm(request.user) # A empty, unbound form
  documents = ImageUpload.objects.all()
  return render_to_response('imageupload.html',
       {'documents': documents, 'form': form,'media':settings.MEDIA_URL},
        context_instance=RequestContext(request)
   )

It used to work properly when I have used only file field in the Model Form. After adding more fields to the model, its not uploading the file. Any suggestion on how to fix this issue?

Thanks in advance Vikram

Was it helpful?

Solution

Just add an else block to your view for form validation. I think that your form is not valid and you do not just print any errors in your template.

if form.is_valid():
    newdoc = ImageUpload(imagefile = request.FILES['imagefile'])
    newdoc.save()
else:
    # do something visible here

Also if your form is valid you could just use form.save() to save the image and the related data instead of creating new ImageUpload object.

Also, your model requires the User object to be saved.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top