Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many files upload in ImageField form - django

My problem is simple. I have template like this:

<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>

Model looks like that:

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

And forms like that (it uses model Image):

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

And view like that:

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

The problem is that I can't upload images. I want to save image in the two seperate instances od Image Model.
I have an error:

'unicode' object has no attribute 'get'

Thanks for any help and response.

Updated for provide more information

like image 543
galuszkak Avatar asked Dec 22 '22 09:12

galuszkak


1 Answers

Man, Django Formsets is what you need:

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

Edited:

The 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})

The 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>
like image 165
nabucosound Avatar answered Jan 13 '23 13:01

nabucosound