summaryrefslogtreecommitdiff
path: root/mirrors/fields.py
blob: 206c9d7d50c0872d2adf52298c5e723ef70c0479 (plain)
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
from IPy import IP

from django import forms
from django.core import validators
from django.core.exceptions import ValidationError
from django.db import models
from south.modelsinspector import add_introspection_rules


class IPNetworkFormField(forms.Field):
    def to_python(self, value):
        if value in validators.EMPTY_VALUES:
            return None
        try:
            value = IP(value)
        except ValueError as e:
            raise ValidationError(str(e))
        return value


class IPNetworkField(models.Field):
    __metaclass__ = models.SubfieldBase
    description = "IPv4 or IPv6 address or subnet"

    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 44
        super(IPNetworkField, self).__init__(*args, **kwargs)

    def get_internal_type(self):
        return "IPAddressField"

    def to_python(self, value):
        if not value:
            return None
        return IP(value)

    def get_prep_value(self, value):
        value = self.to_python(value)
        if not value:
            return None
        return str(value)

    def formfield(self, **kwargs):
        defaults = {'form_class': IPNetworkFormField}
        defaults.update(kwargs)
        return super(IPNetworkField, self).formfield(**defaults)


add_introspection_rules([], ["^mirrors\.fields\.IPNetworkField"])