Search code examples
pythondjangoadmincidr

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.


Solution

  • There are many ways to achieve what you need.

    What I would do is to define net_cidr as a models.CharField.

    Then define a modelform for your model where you are going to implement the clean_net_cidr function.

    class CIDRForm(ModelForm):
        def clean_net_cidr(self):
            # do your magic processing here
    
        class Meta:
            model = CIDR
    

    and then pass that form to the model admin object

    class CIDRAdmin(admin.ModelAdmin):
        form = CIDRForm
    

    UPDATE:

    It seems this is exactly what you need, based on your comments. https://github.com/jimfunk/django-postgresql-netfields

    Among other fields, it includes a CidrAddressField