I need to be able to upload multiple photos at once. How to do it?

models.py

class Location(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) name = models.CharField(max_length=100, verbose_name="Локация", default=u'') photos = models.ImageField(upload_to='photos', null=True) 

forms.py

 class LocationForm(forms.ModelForm): class Meta: model = Location fields = ['name', 'photos'] 

views.py

 class AddLocationPageView(FormView): template_name = 'add_location.html' form_class = LocationForm def form_valid(self, form): form.save() return super(AddLocationPageView, self).form_valid(form) 

    1 answer 1

    With this code structure in any way, as far as I understand. We'll have to make a number of changes.

    First, change the model so that it can store more than one image:

     class Photo(models.Model): image = models.ImageField(upload_to='photos') location = models.ForeignKey(Location, related_name='photos') class Location(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) name = models.CharField(max_length=100, verbose_name="Локация", default=u'') 

    Second, change the shape so that it can take more than one image:

     class LocationForm(forms.Form): name = forms.CharField(label=u'Локация') photos = forms.ImageField(label=u'Π€ΠΎΡ‚ΠΎΠ³Ρ€Π°Ρ„ΠΈΠΈ', widget=forms.FileInput(attrs={'multiple': 'multiple'})) 

    Finally, complicate the boot algorithm:

     from django.shortcuts import render, redirect from django.core.files.base import ContentFile def add_location(request): if request.method == 'GET': form = LocationForm() return render(request, 'add_location.html', {'form': form}) elif request.method == 'POST': form = LocationForm(request.POST, requst.FILES) if form.is_valid(): location = Location.objects.create(user=request.user, name=form.cleaned_data['name']) for f in request.FILES.getlist('photos'): data = f.read() #Если Ρ„Π°ΠΉΠ» Ρ†Π΅Π»ΠΈΠΊΠΎΠΌ умСщаСтся Π² памяти photo = Photo(location=location) photo.image.save(f.name, ContentFile(data)) photo.save() return redirect(location) #Надо ΠΎΠΏΡ€Π΅Π΄Π΅Π»ΠΈΡ‚ΡŒ get_absolute_url() Π² ΠΌΠΎΠ΄Π΅Π»ΠΈ else: return render(request, 'add_location.html', {'form': form}) 
    • Thank you very much, Sergey! - Dennis