Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #models.py
- upload_path = 'images'
- upload_path_to_resize = 'images/resized'
- class Images(models.Model):
- image = models.ImageField(upload_to=upload_path, blank=True, null=True)
- image_url = models.URLField(blank=True, null=True)
- image_resized = models.ImageField(upload_to=upload_path_to_resize,blank=True)
- width = models.PositiveIntegerField(null=True)
- heigth = models.PositiveIntegerField(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))
- self.image_url = None
- super(Images, self).save()
- def resize(self, *args, **kwargs):
- super().save(*args, **kwargs)
- SIZE = self.width, self.heigth)
- if self.width != None or self.heigth !=None:
- pic = Image.open(self.image.path)
- pic.thumbnail(SIZE, Image.LANCZOS)
- pic.save(self.image_resized.path)
- #forms.py
- from django.forms import ModelForm
- from .models import Images
- class ImageForm(ModelForm):
- class Meta:
- model = Images
- fields = ['image', 'image_url']
- class ResizedForm(ModelForm):
- class Meta:
- model = Images
- fields = ['width', 'heigth']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement