'Django admin CIDR type

The problem is that I am working on a Django Admin project, which should be able to accept CIDR format data and put that into database (Postgres).

Let's say I have a model:

##################################################
class CIDR(models.Model):
    ....
    net_cidr = models.IPAddressField(unique=True)
    ....

    def __unicode__(self):
        return self.net_cidr

##################################################

Based on the above code, the net_cidr field in the database is of inet type, which supports the CIDR format data. However, IPAddressField doesn't support CIDR (at least doesn't work for me). If I want to enter something on my admin site like "128.66.0.0/16", Django will pop an error, telling me to "Enter a valid IPv4 address".

I have tried to change the field type to Char, and it works (of course). However, it is not a good idea to set CIDR as varchar in the database.

Basically what I want is to let net_cidr to be able to accpet an IP Range, like "128.66.0.0-128.66.255.255" or a CIDR block "128.66.0.0/16" and save it to database as "128.66.0.0/16".

I think the key part is how to let IPAddressField accept a string type (like an IP range or CIDR block) data. Then I can convert it to CIDR block and save it to database.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source