Advertisement
Guest User

Untitled

a guest
Oct 11th, 2020
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. #models.py
  2. upload_path = 'images'
  3. upload_path_to_resize = 'images/resized'
  4.  
  5.  
  6. class Images(models.Model):
  7. image = models.ImageField(upload_to=upload_path, blank=True, null=True)
  8. image_url = models.URLField(blank=True, null=True)
  9. image_resized = models.ImageField(upload_to=upload_path_to_resize,blank=True)
  10. width = models.PositiveIntegerField(null=True)
  11. heigth = models.PositiveIntegerField(null=True)
  12.  
  13. def clean(self):
  14. if (self.image == None and self.image_url == None ) or (self.image != None and self.image_url != None ):
  15. raise ValidationError('Empty or both blanked')
  16.  
  17. def get_absolute_url(self):
  18. return reverse('image_edit', args=[str(self.id)])
  19.  
  20. def save(self):
  21. if self.image_url and not self.image:
  22. name = str(self.image_url).split('/')[-1]
  23. img = NamedTemporaryFile(delete=True)
  24. img.write(urlopen(self.image_url).read())
  25. img.flush()
  26. self.image.save(name, File(img))
  27. self.image_url = None
  28. super(Images, self).save()
  29.  
  30. def resize(self, *args, **kwargs):
  31. super().save(*args, **kwargs)
  32. SIZE = self.width, self.heigth)
  33. if self.width != None or self.heigth !=None:
  34. pic = Image.open(self.image.path)
  35. pic.thumbnail(SIZE, Image.LANCZOS)
  36. pic.save(self.image_resized.path)
  37. #forms.py
  38. from django.forms import ModelForm
  39. from .models import Images
  40.  
  41. class ImageForm(ModelForm):
  42. class Meta:
  43. model = Images
  44. fields = ['image', 'image_url']
  45.  
  46. class ResizedForm(ModelForm):
  47. class Meta:
  48. model = Images
  49. fields = ['width', 'heigth']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement