Login

Custom model field for Frame or Box

Author:
binishkaspar
Posted:
February 20, 2011
Language:
Python
Version:
1.2
Tags:
field custom-model-field frame
Score:
0 (after 0 ratings)

Purpose

We often need to store x,y, width and height for a model, we can store all these values in same field by having custom field.

How to Use

Save this code in customfields.py and in your model

from customfields import FrameField class MyModel(models,Model) frame = FrameField()

And in your in views, you can use as follows

model = MyModel.objects.get(1) print model.frame.x, model.frame.y, model.frame.width, model.frame.height

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Frame(object):

    #TODO: Missing Validateion and exception raising
    def __init__(self, x, y, width, height):
        self.x = float(x)
        self.y = float(y)
        self.width = float(width)
        self.height = float(height)
    
    @staticmethod    
    def Parse(value):
    
        if value == '' or value is None:
            return Frame(0,0,0,0)
            
        (x, y, width, height) = value.split(',')
        return Frame(x, y, width, height)
        
    def __unicode__(self):
        return "%f,%f,%f,%f" % (self.x, self.y, self.width, self.height)
        

class FrameField(models.Field):

    __metaclass__ = models.SubfieldBase
    
     
    def __init__(self,  *args, **kwargs):
        #self.max_length = 68
        super(FrameField, self).__init__(*args, **kwargs)

    def db_type(self, connection):
        return 'char(%s)' % 68
        
    def to_python(self, value):
        
        if isinstance(value, Frame):
            return value
            
        return Frame.Parse(value) 
        
    def get_prep_value(self, value):
        return self.to_python(value)
        
        
    def get_db_prep_save(self, value, connection):
        return self.to_python(value).__unicode__()
        
    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)

More like this

  1. FieldsetForm by Ciantic 8 years, 3 months ago
  2. dropbox integration by ivarne 3 years, 4 months ago
  3. Accessing URL variable from within a Form by blacktav 1 year, 11 months ago
  4. View Permission Decorator Helper by jgeewax 7 years ago
  5. ThumbnailMixIn by johan 6 years, 3 months ago

Comments

Please login first before commenting.