File: formfields.py

package info (click to toggle)
django-macaddress 1.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 156 kB
  • sloc: python: 203; makefile: 7
file content (25 lines) | stat: -rw-r--r-- 821 bytes parent folder | download
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
from django.core.validators import EMPTY_VALUES
from django.forms import Field
from django.forms.utils import ValidationError
from django.utils.translation import gettext_lazy as _
from netaddr import EUI, AddrFormatError


class MACAddressField(Field):
    default_error_messages = {
        "invalid": _("Enter a valid MAC Address."),
    }

    def clean(self, value):
        """
        Validates that EUI() can be called on the input. Returns the result
        of EUI(). Returns None for empty values.
        """
        value = super().clean(value)
        if value in EMPTY_VALUES:
            return None
        try:
            value = EUI(str(value), version=48)
        except (ValueError, TypeError, AddrFormatError):
            raise ValidationError(self.error_messages["invalid"])
        return value