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.