MoDDem MoDDem - 27 days ago 7
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():
try:
f = request.FILES['image']
post = form.save(commit=False)
post.image.save(f.name, f)
post.date = timezone.now()
post.save()
except MultiValueDictKeyError:
post = form.save(commit=False)
post.date = timezone.now()
post.save()
return redirect('home:index')
else:
form = PostForm()
return render(request, 'home/edit_post.html',
{'form': form, 'error_message': 'something error message'})
else:
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>
<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>
<div class="input-group" style="margin-bottom: 10px; margin-left: 40%">
{{ form.image }}
</div>
<button type="submit" class="save btn btn-default" style="margin-left: 45.2%; margin-bottom: 20px">edit</button>
</form>


I would be happy for any help

Answer

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