~widelands-dev/widelands-website/django_staticfiles

« back to all changes in this revision

Viewing changes to wlggz/fields.py

  • Committer: timo
  • Date: 2010-06-03 14:21:21 UTC
  • mto: This revision was merged to the branch mainline in revision 218.
  • Revision ID: timo@athin-20100603142121-65pr9u44g3lsmxoi
add first version of wlggz app

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""
 
2
Details about AutoOneToOneField:
 
3
    http://softwaremaniacs.org/blog/2007/03/07/auto-one-to-one-field/
 
4
"""
 
5
 
 
6
from StringIO import StringIO
 
7
import logging
 
8
 
 
9
from django.db.models import OneToOneField
 
10
from django.db.models.fields.related import SingleRelatedObjectDescriptor 
 
11
from django.db import models
 
12
from django.core.files.uploadedfile import SimpleUploadedFile
 
13
 
 
14
 
 
15
class AutoSingleRelatedObjectDescriptor(SingleRelatedObjectDescriptor):
 
16
    def __get__(self, instance, instance_type=None):
 
17
        try:
 
18
            return super(AutoSingleRelatedObjectDescriptor, self).__get__(instance, instance_type)
 
19
        except self.related.model.DoesNotExist:
 
20
            obj = self.related.model(**{self.related.field.name: instance})
 
21
            obj.save()
 
22
            return obj
 
23
 
 
24
 
 
25
class AutoOneToOneField(OneToOneField):
 
26
    """
 
27
    OneToOneField creates dependent object on first request from parent object
 
28
    if dependent oject has not created yet.
 
29
    """
 
30
 
 
31
    def contribute_to_related_class(self, cls, related):
 
32
        setattr(cls, related.get_accessor_name(), AutoSingleRelatedObjectDescriptor(related))
 
33
        #if not cls._meta.one_to_one_field:
 
34
            #cls._meta.one_to_one_field = self
 
35
 
 
36
 
 
37
class ExtendedImageField(models.ImageField):
 
38
    """
 
39
    Extended ImageField that can resize image before saving it.
 
40
    """
 
41
    def __init__(self, *args, **kwargs):
 
42
        self.width = kwargs.pop('width', None)
 
43
        self.height = kwargs.pop('height', None)
 
44
        super(ExtendedImageField, self).__init__(*args, **kwargs)
 
45
 
 
46
    
 
47
    def save_form_data(self, instance, data):
 
48
        if data and self.width and self.height:
 
49
            if instance.avatar:
 
50
                instance.avatar.delete()
 
51
 
 
52
            content = self.resize_image(data.read(), width=self.width, height=self.height)
 
53
            data = SimpleUploadedFile(instance.user.username + ".png", content, data.content_type)
 
54
            super(ExtendedImageField, self).save_form_data(instance, data)
 
55
 
 
56
 
 
57
    def resize_image(self, rawdata, width, height):
 
58
        """
 
59
        Resize image to fit it into (width, height) box.
 
60
        """
 
61
 
 
62
        try:
 
63
            import Image
 
64
        except ImportError:
 
65
            from PIL import Image
 
66
 
 
67
        image = Image.open(StringIO(rawdata))
 
68
        try:
 
69
            oldw, oldh = image.size
 
70
            
 
71
            if oldw > width or oldh > height:
 
72
                if oldw >= oldh:
 
73
                    x = int(round((oldw - oldh) / 2.0))
 
74
                    image = image.crop((x, 0, (x + oldh) - 1, oldh - 1))
 
75
                else:
 
76
                    y = int(round((oldh - oldw) / 2.0))
 
77
                    image = image.crop((0, y, oldw - 1, (y + oldw) - 1))
 
78
                image = image.resize((width, height), resample=Image.ANTIALIAS)
 
79
        except Exception, err:
 
80
            logging.error(err)
 
81
            return ''
 
82
 
 
83
        string = StringIO()
 
84
        image.save(string, format='PNG')
 
85
        return string.getvalue()