Uploading many files to an ImageField form - django

My problem is simple. I have a template:

<form enctype="multipart/form-data" action="{% url offers.views.add_offer %}" method="post"> <input type="file" name="image1" /> <input type="file" name="image2" /> <input type="submit" value="Add" /> </form> 

The model is as follows:

 class Image(models.Model): image = models.ImageField(upload_to='uploads/images/offers/') 

And forms like this (it uses a model image):

 class ImageForm(ModelForm): class Meta: model = Image 

And look like this:

  for f in request.FILES: # imageform: image = ImageForm(request.POST, f) image.save() 

The problem is that I cannot upload images. I want to save the image in two separate instances of the image model.
I have an error:

'unicode' object has no attribute 'get'

Thanks for any help and answer.

Updated for more information.

+4
source share
3 answers

Man, Django Formsets is what you need:

http://docs.djangoproject.com/en/dev/topics/forms/formsets/

Edited

View:

 def manage_images(request): ImageFormSet = formset_factory(ImageForm) if request.method == 'POST': formset = ImageFormSet(request.POST, request.FILES) if formset.is_valid(): # do something with the formset.cleaned_data else: formset = ImageFormSet() return render_to_response('manage_images.html', {'formset': formset}) 

Template:

 <form enctype="multipart/form-data" action="{% url offers.views.add_offer %}" method="post"> {{ formset.management_form }} <table> {% for form in formset.forms %} {{ form }} {% endfor %} </table> </form> 
+8
source

here you will find documents for downloading files .

I save my image in the form of save () - a method like this:

 def save(self): if self.cleaned_data.get('galleryname'): if self.cleaned_data.get('images1'): path = 'images/'+ urlify(self.cleaned_data.get('galleryname'))+self.cleaned_data.get('images1').name destination = open(s.MEDIA_ROOT+path, 'wb+') for chunk in self.cleaned_data.get('images1').chunks(): destination.write(chunk) p = Photo() p.picture="./"+path p.save() 

and in the view I have

 form = CompleteSubscriptionForm(request.POST, request.FILES, error_class=DivErrorList) if form.is_valid(): # All validation rules pass form.save() 
+2
source

Why do you think this will work? You iterate through request.FILES and try to instantiate the form at each iteration by passing in a file object. This is nothing like the documentation that tells you to pass all request.FILES in.

Edited after comment. Look, you did not give us a lot of information to continue. Does your model have one or two images? Why are you trying to process two images separately? Are you trying to create two separate instances of the model or one with two images? What exactly are you trying to do?

Basically you just want to do this:

 form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() 

and what is he.

+1
source

All Articles