0

I have modek `from tempfile import NamedTemporaryFile

#models.py
upload_path = 'images'

class Image(models.Model):
    image = models.ImageField(upload_to=upload_path, blank=True, null=True)
    image_url = models.URLField(blank=True, null=True)

    def clean(self):
        if (self.image == None and self.image_url == None ) or (self.image != None and self.image_url != None ):
            raise ValidationError('Empty or both blanked')

    def get_absolute_url(self):
        return reverse('image_edit', args=[str(self.id)])

    def save(self):
        if self.image_url and not self.image:
            name = str(self.image_url).split('/')[-1]
            img = NamedTemporaryFile(delete=True)
            img.write(urlopen(self.image_url).read())
            img.flush()
            self.image.save(name, File(img))
            super(Image, self).save()

This model loads the link url into the ImageField.

#forms.py
class ImageForm(ModelForm):
class Meta:
    model = Image
    fields = ['image', 'image_url']

This is my form to add images.

#views.py
class DetailImage(UpdateView):
model = Image
form_class = ImageForm
template_name = 'image_edit.html'
context_object_name = 'image'

How can I resize images so that the original files are retained, and only images changed in width and height are displayed in the backend?

messageman
  • 23
  • 1
  • 7
  • follow this comment post https://stackoverflow.com/questions/7970637/how-to-resize-the-new-uploaded-images-using-pil-before-saving – Kishan Parmar Oct 10 '20 at 15:01
  • @KishanParmar need resize after upload, it doesn't quite suit me – messageman Oct 10 '20 at 15:06
  • What are the changed images for? Probably you are searching for something like [django-stdimage](https://github.com/codingjoe/django-stdimage). It generates and manages thumbnails which are generated after upload and stored. Of course you could also rebuild the behaviour yourself. – Denis Cornehl Oct 11 '20 at 07:22

0 Answers0