~widelands-dev/widelands-website/django_staticfiles

« back to all changes in this revision

Viewing changes to wlprofile/fields.py

  • Committer: franku
  • Date: 2016-12-13 18:28:51 UTC
  • mto: This revision was merged to the branch mainline in revision 443.
  • Revision ID: somal@arcor.de-20161213182851-bo5ebf8pdvw5beua
run the script

Show diffs side-by-side

added added

removed removed

Lines of Context:
3
3
import logging
4
4
from django.core.files.uploadedfile import SimpleUploadedFile
5
5
 
 
6
 
6
7
class ExtendedImageField(models.ImageField):
7
 
    """
8
 
    Extended ImageField that can resize image before saving it.
9
 
    """
 
8
    """Extended ImageField that can resize image before saving it."""
 
9
 
10
10
    def __init__(self, *args, **kwargs):
11
11
        self.width = kwargs.pop('width', None)
12
12
        self.height = kwargs.pop('height', None)
13
13
        super(ExtendedImageField, self).__init__(*args, **kwargs)
14
14
 
15
 
 
16
15
    def save_form_data(self, instance, data):
17
16
        if data is not None and data != self.default:
18
17
            if not data:
19
18
                data = self.default
20
19
                if instance.avatar != self.default:
21
 
                        instance.avatar.delete()
 
20
                    instance.avatar.delete()
22
21
            else:
23
22
                if hasattr(data, 'read') and self.width and self.height:
24
 
                    content = self.resize_image(data.read(), width=self.width, height=self.height)
25
 
                    data = SimpleUploadedFile(instance.user.username + ".png", content, "image/png")
 
23
                    content = self.resize_image(
 
24
                        data.read(), width=self.width, height=self.height)
 
25
                    data = SimpleUploadedFile(
 
26
                        instance.user.username + '.png', content, 'image/png')
26
27
            super(ExtendedImageField, self).save_form_data(instance, data)
27
28
 
28
 
 
29
29
    def resize_image(self, rawdata, width, height):
30
 
        """
31
 
        Resize image to fit it into (width, height) box.
32
 
        """
 
30
        """Resize image to fit it into (width, height) box."""
33
31
        from PIL import Image
34
32
 
35
33
        image = Image.open(StringIO(rawdata))