Login

Storing IP address ModelField as Integer, without nasty hacks..

Author:
sleepycal
Posted:
July 19, 2011
Language:
Python
Version:
1.2
Score:
-2 (after 2 ratings)

See code

 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
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
Notes:
 - ip field MUST be manually altered to be an unsigned int.

Usage:

class SessionIP(models.Model):
    ip = RealIPAddressField(db_index = True)

_s = SessionIP.objects.get(ip='1.2.3.4') # works
_s.ip = '2.3.4.5'; _s.save() # works
SessionIP.objects.filter(id = _s.id).update(ip = '1.2.3.4') # doesn't work!

"""


class RealIPAddressField(models.Field):
    __metaclass__ = models.SubfieldBase

    description = _("Real IP Address field")

    empty_strings_allowed = False
    default_error_messages = {
        'invalid': _('Please enter a valid IP Address (x.x.x.x)'),
    }

    def get_internal_type(self):
        return "IntegerField"

    def to_python(self, value):
        if value is None:
            return value

        elif isinstance(value, str) or isinstance(value, unicode):
            return value

        elif isinstance(value, int) or isinstance(value, long):
            return iptools.long2ip(value)

        assert False, "This should never happen"

    def get_db_prep_value(self, value, connection, prepared=False):
        if value is None:
            return value

        elif isinstance(value, str):
            return iptools.ip2long(value)

        elif isinstance(value, int) or isinstance(value, long):
            return value

    def get_prep_lookup(self, lookup_type, value):
        if value is None:
            return value

        elif isinstance(value, str) or isinstance(value, unicode):
            return iptools.ip2long(value)

        elif isinstance(value, int):
            return int

        else:
            assert False, "This should never happen"
            

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.