• Как сохранить из формы в модель несколько картинок?

    В одну модель сохранить несколько кортинок нельзя(если поле для картинок одно).
    Для сохранения картинок нужно создать новую модель.
    models.py
    class Advert(models.Model):
        category = models.TextField()
        title = models.CharField(max_length=64)
        description = models.CharField(max_length=900)
        date = models.DateTimeField(auto_now_add=True, null=True)
    
    
    class AdvertImage(models.Model):
        advert = models.ForeignKey(Advert)
        photo = models.ImageField(upload_to='uploads/')

    forms.py
    class AddAdvertForm(ModelForm):
        class Meta:
            model = Advert
            fields = '__all__'
    
    
    class AdvertImagesForm(forms.Form):
    
        photos = forms.FileField(widget=widgets.FileInput(attrs={'multiple': True}))
    
        def __init__(self, *args, **kwargs):
            if 'request' in kwargs:
                self.request = kwargs.pop('request')
            super(AdvertImagesForm, self).__init__(*args, **kwargs)
    
        def clean_photos(self):
            # Остаются только картинки
            photos = [photo for photo in self.request.FILES.getlist('photos') if 'image' in photo.content_type]
            # Если среди загруженных файлов картинок нет, то исключение
            if len(photos) == 0:
                raise forms.ValidationError(u'Not found uploaded photos.')
            return photos
    
        def save_for(self, advert):
            for photo in self.cleaned_data['photos']:
                AdvertImage(photo=photo, advert=advert).save()

    views.py
    class CreateAdvertView(View):
        template_name = 'bulletinboard/add_advert.html'
        form_class = AddAdvertForm
        form_images_class = AdvertImagesForm
        model = Advert
    
        def get(self, request):
            form = self.form_class()
            form_images = self.form_images_class()
            return render(request, self.template_name, {'form': form, 'form_images': form_images})
    
        def post(self, request):
            form = self.form_class(request.POST)
            form_images = self.form_images_class(request.POST, request.FILES, request=request)
            if form.is_valid() and form_images.is_valid():
                advert = form.save()
                form_images.save_for(advert)
                return HttpResponseRedirect('/')
            return render(request, self.template_name, {'form': form, 'form_images': form_images})
    Ответ написан
    7 комментариев