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?