Upload multiples Images in Django

2

I am trying to upload multiple images in a django form. So far you get to the point of getting this error InMemoryUploadedFile' object has no attribute 'get' indicating that the problem is in line imgform.save() of the view.

This is my simplified code:

realstate.models

from django.db import models

class Property(models.Model):
    title = models.CharField()

class PropertyImage(models.Model):
    property = models.ForeignKey(Property, related_name='images')
    image = models.ImageField()

realstate.forms

from realstate.models import Property, PropertyImage

class AddPropertyForm(forms.ModelForm):

        model = Property
        fields = '__all__'

class ImageForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ImageForm, self).__init__(*args, **kwargs)
        self.fields['image'].widget.attrs['multiple'] = True

    class Meta:
        model = PropertyImage
        fields = '__all__'

realstate.views

def add_property(request):
    if request.method == 'POST':
        form = AddPropertyForm(request.POST)
        files = request.FILES.getlist('image')
        print(files)
        if form.is_valid():
            for f in files:
                imgform = ImageForm(f)
                if imgform.is_valid:
                    imgform.save()
            form.save()
        return HttpResponse("image upload success")
    else:
        form = AddPropertyForm()
        imgform = ImageForm()

    return render(request, 'realstate/admin-property-add.html', {'form': form, 'imgform': imgform})

template

<form action="{% url 'realstate:add-property' %}" method="post" enctype="multipart/form-data"> {% csrf_token %}
    {{ form.title }}
    {{ imgform.image }}
</form>

The debug says that the error is in the view at the time of doing imgform.save , but honestly I'm not clear on how to proceed because generally the solutions I found say something like:

files = request.FILES.getlist('image')
for f in files:
  #Haz algo con file...

And there's the detail, I do not know what I have to do with file to keep it in the database.

    
asked by Javier Cárdenas 31.10.2016 в 00:32
source

1 answer

2

This way the images are saved

class ImagenCreateView(CreateView):
        model = imagen
        fields = "__all__"

        def form_valid(self, form):
            self.object = form.save()
            files = [serialize(self.object)]
            data = {'files': files}
            response = JSONResponse(data, mimetype=response_mimetype(self.request))
            response['Content-Disposition'] = 'inline; filename=files.json'
            return response

        def form_invalid(self, form):
            data = json.dump(form.errors)
            return HttpResponse(content=data, status=400, content_type='application/json')

And this is my response

# encoding: utf-8
from django.http import HttpResponse
import json

MIMEANY = '*/*'
MIMEJSON = 'application/json'
MIMETEXT = 'text/plain'


def response_mimetype(request):
    """response_mimetype -- Return a proper response mimetype, accordingly to
    what the client accepts, as available in the 'HTTP_ACCEPT' header.

    request -- a HttpRequest instance.

    """
    can_json = MIMEJSON in request.META['HTTP_ACCEPT']
    can_json |= MIMEANY in request.META['HTTP_ACCEPT']
    return MIMEJSON if can_json else MIMETEXT


class JSONResponse(HttpResponse):
    """JSONResponse -- Extends HTTPResponse to handle JSON format response.

    This response can be used in any view that should return a json stream of
    data.

    Usage:

        def a_iew(request):
            content = {'key': 'value'}
            return JSONResponse(content, mimetype=response_mimetype(request))

    """
    def __init__(self, obj='', json_opts=None, mimetype=MIMEJSON, *args, **kwargs):
        json_opts = json_opts if isinstance(json_opts, dict) else {}
        content = json.dumps(obj, **json_opts)
        super(JSONResponse, self).__init__(content, mimetype, *args, **kwargs)
    
answered by 31.10.2016 в 01:04