Opened 4 years ago
Last modified 8 months ago
#31710 closed Cleanup/optimization
Multi upload with Imagefield allows non image files to be uploaded — at Version 1
Reported by: | nawaik | Owned by: | nobody |
---|---|---|---|
Component: | Documentation | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Simon Brulhart | Triage Stage: | Accepted |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description (last modified by )
When following the multiple files documentation:
https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/#uploading-multiple-files
If you change:
file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
To:
file_field = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
The file input field looks like this:
<input type="file" name="file_field" multiple="" accept="image/*" required="" id="id_file_field">
If you do inspect element and remove accept="image/*" so it looks like this:
<input type="file" name="file_field" multiple="" required="" id="id_file_field">
If you then only add 1 .txt file everything works fine and you get an error:
"Upload a valid image. The file you uploaded was either not an image or a corrupted image."
However if you upload multiple .txt files or a mix of images and files nothing gets checked and you are able to upload .txt files in imagefields.
I tried this with a fresh project and was able to reproduce the problem.
This is how it looks in the sqlite db:
id image post_id 4 products/testnow_copy_2.txt 2
Code I used to recreate the problem:
Models.py
from django.db import models class Product(models.Model): title = models.CharField(max_length=50) class Images(models.Model): post = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to='products/') def __str__(self): return self.post.title
Forms.py
from django import forms from .models import Product class MultiPhotoForm(forms.ModelForm): file_field = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Product fields = ['title']
Views.py
from django.shortcuts import render from .forms import MultiPhotoForm from .models import Images, Product def MultiUploadView(request): template_name = 'test.html' if request.method == "POST": form = MultiPhotoForm(request.POST or None, request.FILES or None) files = request.FILES.getlist('file_field') if form.is_valid(): title = form.cleaned_data['title'] product = Product.objects.create(title = title) for i in files: Images.objects.create(post=product,image=i) else: form = MultiPhotoForm() return render(request, template_name, {'form': form})