MoDDem MoDDem - 1 year ago 103
Python Question

Django multiple upload images doesn't work

I'm trying to add a multiple upload, but where i upload 2 or more images can be added only one
views with add files:

def post_new(request):
if request.method == "POST":
form = PostForm(request.POST, request.FILES)
if form.is_valid():
f = request.FILES['image']
post =, f) =
except MultiValueDictKeyError:
post = =
return redirect('home:index')
form = PostForm()
return render(request, 'home/edit_post.html',
{'form': form, 'error_message': 'something error message'})
form = PostForm()
return render(request, 'home/edit_post.html', {'form': form})

and form where i get image form:

class PostForm(forms.ModelForm):

class Meta:
model = Post
fields = ['title', 'text', 'image']

and I also tried this:

image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

But it did not help

own model where is the image:

class Post(models.Model):
title = models.CharField()
date = models.DateTimeField(editable=True, null=True)
text = models.TextField()
image = models.ImageField(null=True, blank=True, upload_to='my-images')
is_super = models.IntegerField(default=0)

template edit_post:

<form action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
{% if error_message %}
<p><strong style="margin-left: 35%; color: red">{{ error_message }}</strong></p>
{% endif %}
<div class="input-group" style="margin-bottom: 10px; margin-left: 38.5%">
<label for="id_title" style="margin-left: 35%">title</label>
<input style="text-align: center" value="{{ form.title.value }}" class="form-control" placeholder="****" id="id_title" name="title" type="text">
<div class="input-group" style="margin-bottom: 10px; margin-left: 30%">
<label for="id_text" style="margin-left: 42%">text</label>
<textarea style="resize: none; width: 500px; height: 250px" placeholder="***" class="form-control" id="id_text" name="text">{{ form.text.value }}</textarea>
<div class="input-group" style="margin-bottom: 10px; margin-left: 40%">
{{ form.image }}
<button type="submit" class="save btn btn-default" style="margin-left: 45.2%; margin-bottom: 20px">edit</button>

I would be happy for any help

Answer Source

Your Post model a a single image field, so what would you do of other images? If you want zero, one or more images per post, you need a distinct Image model with a foreign key on Post, and then use a Formset for the images

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download