Login

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

Author:
sleepycal
Posted:
July 19, 2011
Language:
Python
Version:
1.2
Tags:
ip integer address modelfield int
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. Test IP against IP address+Subnet whitelist by mtigas 5 years, 10 months ago
  2. Tuned IPAddressField with IPv4 & IPv6 support by diverman 6 years, 2 months ago
  3. Block IP addresses by pill 7 years ago
  4. Globs for INTERNAL_IPS by kcarnold 6 years, 2 months ago
  5. Tuned IPAddressField with IPv4 & IPv6 support using Postgres Network Field type by illsci 6 years, 1 month ago

Comments

Please login first before commenting.