Snippet List
Based on #1381
Use this piece of code to add IPv4/IPv6 and network support to Django.
An IPAddressField allows you to find IP's for a given subnet. An IPNetworkField allows you to find a subnet for a given IP or find a subnet within a subnet.
For starters, simply paste it into a new file in your app called fields.py.
IPAddressField example
# models.py
from fields import IPAddressField
class IPTest(models.Model):
ip = IPAddressField()
To search for an IP within a given subnet
from ipaddr import IPNetwork
IPTest.objects.filter(ip__in=IPNetwork('10.0.0.0/24'))
IPNetworkField example
# models.py
from fields import IPNetworkField, IPNetworkQuerySet
class IPTest(models.Model):
objects = IPNetworkQuerySet.as_manager()
network = IPNetworkField()
To search for a subnet with a given IP
from ipaddr import IPAddress
IPTest.objects.network('network', IPAddress('10.0.0.1'))
- cidr
- ipv4
- ipv6
- ipaddress
- ipnetwork
CIDR ( http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing ) is a well-known IP range syntax. This CIDR_LIST class can be used to make ranges of IPs considered "internal" for Django's debugging and security purposes. (Django only ever needs to do "ip in INTERNAL_IPS" so __contains__ is sufficient for the purpose.)
For example, to make localhost and the entire block of 10.0.0.* considered to be internal, use:
INTERNAL_IPS = CIDR_LIST([
'127.0.0.1',
'10.0.0.0/24'
])
- debugging
- security
- ip
- cidr
- internal_ips
A simple addition to the settings.py file of your project to allow you to easily specify entire network ranges as internal. This is especially useful in conjunction with other tools such as the [Django Debug Toolbar](http://github.com/robhudson/django-debug-toolbar/tree/master).
After you set this up, the following test should pass
test_str = """
>>> '192.168.1.5' in INTERNAL_IPS
True
>>> '192.168.3.5' in INTERNAL_IPS
FALSE
"""
Requirements
------------
* The [IPy module](http://software.inl.fr/trac/wiki/IPy)
Acknowledgements
----------------
Jeremy Dunck: The initial code for this idea is by Jeremy and in [Django ticket #3237](http://code.djangoproject.com/ticket/3237). I just changed the module and altered the use of the list superclass slightly. I mainly wanted to put the code here for safe keeping. Thanks Jeremy!
- settings
- ip-addresses
- cidr
- internal-ips
3 snippets posted so far.