django.core.exceptions.ValidationError - python examples

Here are the examples of the python api django.core.exceptions.ValidationError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

1 2 3
3 View Complete Implementation : fields.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean(self, value):
        if not value:
            return None
        # Avoid circular imports
        from maasterver.models.node import Node

        try:
            return self.queryset.get(Q(system_id=value) | Q(hostname=value))
        except Node.DoesNotExist:
            raise ValidationError(
                "Select a valid choice. "
                "%s is not one of the available choices." % value
            )

3 View Complete Implementation : interface.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean_parents(self):
        """Validate that child interfaces cannot be created unless at least one
        parent is present.
        """
        parents = self.get_clean_parents()
        if parents is None:
            return
        # Ensure support for parthenogenesis.
        if len(parents) < 1:
            raise ValidationError(
                "A %s interface must have one or more parents."
                % self.Meta.model.get_type()
            )
        return parents

3 View Complete Implementation : resourcepool.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def delete(self):
        if self.is_default():
            raise ValidationError(
                "This is the default pool, it cannot be deleted."
            )
        if self.node_set.exists():
            raise ValidationError(
                "Pool has machines in it, it cannot be deleted."
            )
        super().delete()

3 View Complete Implementation : interface.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean(self):
        link_connected = self.cleaned_data.get("link_connected")
        link_speed = self.cleaned_data.get("link_speed")
        if (
            link_connected is not None
            and not link_connected
            and not self.link_connected
            and link_speed is not None
            and link_speed != 0
        ):
            raise ValidationError(
                "link_speed cannot be set when link_connected is false."
            )
        return super().clean()

3 View Complete Implementation : script.py
Copyright GNU Affero General Public License v3.0
Author : maas
def translate_script_parallel(parallel):
    if isinstance(parallel, int) or parallel.isdigit():
        ret = int(parallel)
        for script_parallel_id, _ in SCRIPT_PARALLEL_CHOICES:
            if ret == script_parallel_id:
                return ret
        raise ValidationError("Invalid script parallel numeric value.")
    elif parallel in ["disabled", "none"]:
        return SCRIPT_PARALLEL.DISABLED
    elif parallel in ["instance", "name"]:
        return SCRIPT_PARALLEL.INSTANCE
    elif parallel in ["any", "enabled"]:
        return SCRIPT_PARALLEL.ANY
    else:
        raise ValidationError(
            "Script parallel must be disabled, instance, or any."
        )

3 View Complete Implementation : test_middleware.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_returns_ValidationError_message_dict_as_json(self):
        exception_dict = {"hostname": ["invalid"]}
        exception = ValidationError(exception_dict)
        request = self.make_fake_request()
        response = self.process_exception(request, exception)
        self.astertIsInstance(response.content, bytes)
        self.astertEqual(
            exception_dict,
            json.loads(response.content.decode(settings.DEFAULT_CHARSET)),
        )
        self.astertIn("application/json", response["Content-Type"])

3 View Complete Implementation : domain.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def update_dnsdata(self, params):
        domain = self._get_domain_or_permission_error(params)
        dnsdata = DNSData.objects.get(
            id=params["dnsdata_id"], dnsresource_id=params["dnsresource_id"]
        )
        form = DNSDataForm(data=params, instance=dnsdata)
        if form.is_valid():
            form.save()
        else:
            raise ValidationError(form.errors)
        return self.full_dehydrate(domain)

3 View Complete Implementation : sshkey.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean(self, *args, **kwargs):
        """Make sure there are no duplicate keys.

        Note that this could have been done with Meta.unique_together,
        but it doesn't work for big keys, since the long text strings
        can't be indexed.
        """
        super().clean(*args, **kwargs)
        if not self._state.has_changed("key"):
            return

        existing_key = SSHKey.objects.filter(
            keysource=self.keysource, user=self.user, key=self.key
        )
        if existing_key.exists():
            raise ValidationError(
                "This key has already been added for this user."
            )

3 View Complete Implementation : fields.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def _clean_addr(self, value):
        try:
            addr = IPAddress(value)
        except ValueError:
            return
        except AddrFormatError:
            raise ValidationError("Invalid IP address: %s." % value)
        else:
            return str(addr)

3 View Complete Implementation : interface.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean_link_connected_speed(self, cleaned_data):
        link_connected = cleaned_data.get("link_connected")
        link_speed = cleaned_data.get("link_speed")
        obj_link_connected = getattr(self, "link_connected", None)
        if (
            link_connected is not None
            and not link_connected
            and obj_link_connected is not None
            and not obj_link_connected
            and link_speed is not None
            and link_speed != 0
        ):
            raise ValidationError(
                "link_speed cannot be set when link_connected is false."
            )

3 View Complete Implementation : interface.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean(self):
        link_connected = self.cleaned_data.get("link_connected")
        link_speed = self.cleaned_data.get("link_speed")
        if (
            link_connected is not None
            and not link_connected
            and not self.link_connected
            and link_speed is not None
            and link_speed != 0
        ):
            raise ValidationError(
                "link_speed cannot be set when link_connected is false."
            )
        return super().clean()

3 View Complete Implementation : packagerepository.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean_arches(self):
        arches = []
        for value in self.cleaned_data.get("arches", []):
            arches.extend([s.strip() for s in value.split(",")])
        known_arches = set(PackageRepository.objects.get_known_architectures())
        for value in arches:
            if value not in known_arches:
                raise ValidationError(
                    "'%s' is not a valid architecture. Known architectures: "
                    "%s" % (value, ", ".join(sorted(known_arches)))
                )
        # If no arches provided, use MAIN_ARCHES.
        if len(arches) == 0:
            arches = PackageRepository.MAIN_ARCHES
        return arches

3 View Complete Implementation : space.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean_name(self):
        reserved = re.compile(r"^space-\d+$")
        if self.name is not None and self.name != "":
            if self.name == Space.UNDEFINED:
                raise ValidationError({"name": ["Reserved space name."]})
            if reserved.search(self.name):
                if self.id is None or self.name != "space-%d" % self.id:
                    raise ValidationError({"name": ["Reserved space name."]})
        elif self.id is not None:
            # Since we are not creating the space, force the (null or empty)
            # name to be the default name.
            self.name = "space-%d" % self.id

3 View Complete Implementation : machine.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def create_bridge(self, params):
        """Create bridge interface."""
        node = self._get_node_or_permission_error(
            params, permission=self._meta.edit_permission
        )
        if node.status == NODE_STATUS.ALLOCATED:
            form = AcquiredBridgeInterfaceForm(node=node, data=params)
        else:
            form = BridgeInterfaceForm(node=node, data=params)
        if form.is_valid():
            interface = form.save()
            self._update_obj_tags(interface, params)
            self._create_link_on_interface(interface, params)
        else:
            raise ValidationError(form.errors)

3 View Complete Implementation : filesystemgroup.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def add_parsation(self, parsation, fstype):
        """Adds a parsation to the array, creates the correct filesystem."""
        # Avoid circular import.
        from maasterver.models.filesystem import Filesystem

        if parsation.get_node() != self.get_node():
            raise ValidationError(
                "Parsation must be on a device from the same node as the rest "
                "of the array."
            )
        elif parsation.get_effective_filesystem() is not None:
            raise ValidationError(
                "There is another filesystem on this parsation."
            )
        else:
            Filesystem.objects.create(
                parsation=parsation, fstype=fstype, filesystem_group=self
            )
        return self

3 View Complete Implementation : domain.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def delete_address_record(self, params):
        domain = self._get_domain_or_permission_error(params)
        dnsresource = DNSResource.objects.get(
            domain=domain, id=params["dnsresource_id"]
        )
        ip_addresses = dnsresource.get_addresses()
        ip_addresses.remove(params["rrdata"])
        params["ip_addresses"] = " ".join(ip_addresses)
        form = DNSResourceForm(
            data=params, user=self.user, instance=dnsresource
        )
        if form.is_valid():
            form.save()
        else:
            raise ValidationError(form.errors)

3 View Complete Implementation : script.py
Copyright GNU Affero General Public License v3.0
Author : maas
def translate_script_type(script_type):
    if isinstance(script_type, int) or script_type.isdigit():
        ret = int(script_type)
        for script_type_id, _ in SCRIPT_TYPE_CHOICES:
            if ret == script_type_id:
                return ret
        raise ValidationError("Invalid script type numeric value.")
    elif script_type in ["test", "testing"]:
        return SCRIPT_TYPE.TESTING
    elif script_type in ["commission", "commissioning"]:
        return SCRIPT_TYPE.COMMISSIONING
    else:
        raise ValidationError("Script type must be testing or commissioning")

3 View Complete Implementation : sslkey.py
Copyright GNU Affero General Public License v3.0
Author : maas
def validate_ssl_key(value):
    """Validate that the given value contains a valid SSL key."""
    try:
        crypto.load_certificate(crypto.FILETYPE_PEM, value)
    except Exception:
        # crypto.load_certificate raises all sorts of exceptions.
        # Here, we catch them all and return a ValidationError since this
        # method only aims at validating keys and not return the exact cause of
        # the failure.
        logger.exception("Invalid SSL key.")
        raise ValidationError("Invalid SSL key.")

3 View Complete Implementation : physicalblockdevice.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def __init__(self, *args, **kwargs):
        if kwargs:
            # only check when kwargs are pasted, which is the normal case when
            # objects are created. If they're loaded from the DB, args get
            # pasted instead.
            node = kwargs.get("node")
            numa_node = kwargs.get("numa_node")
            if node and numa_node:
                raise ValidationError("Can't set both node and numa_node")
            if not numa_node:
                kwargs["numa_node"] = node.default_numanode
            elif not node:
                kwargs["node"] = numa_node.node
        super().__init__(*args, **kwargs)

3 View Complete Implementation : settings.py
Copyright GNU Affero General Public License v3.0
Author : maas
def validate_missing_boot_images(value):
    """Raise `ValidationError` when the value is equal to '---'. This is
    used when no boot images exist on all clusters, so the config value cannot
    be changed."""
    if value == "---":
        raise ValidationError(
            "Unable to determine supported operating systems, "
            "due to missing boot images."
        )

3 View Complete Implementation : machine.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def create_vlan(self, params):
        """Create VLAN interface."""
        node = self._get_node_or_permission_error(
            params, permission=self._meta.edit_permission
        )
        params["parents"] = [params.pop("parent")]
        form = VLANInterfaceForm(node=node, data=params)
        if form.is_valid():
            interface = form.save()
            self._update_obj_tags(interface, params)
            self._create_link_on_interface(interface, params)
        else:
            raise ValidationError(form.errors)

3 View Complete Implementation : device.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def update_interface(self, params):
        """Update the interface."""
        device = self.get_object(params, permission=self._meta.edit_permission)
        interface = Interface.objects.get(
            node=device, id=params["interface_id"]
        )
        interface_form = InterfaceForm.get_interface_form(interface.type)
        form = interface_form(instance=interface, data=params)
        if form.is_valid():
            interface = form.save()
            self._configure_interface(interface, params)
            return self.full_dehydrate(reload_object(device))
        else:
            raise ValidationError(form.errors)

3 View Complete Implementation : fields.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def to_python(self, value):
        # Avoid circular imports
        from maasterver.models.node import Node

        try:
            return self.queryset.get(Q(system_id=value) | Q(hostname=value))
        except Node.DoesNotExist:
            raise ValidationError(
                "Select a valid choice. "
                "%s is not one of the available choices." % value
            )

3 View Complete Implementation : storage_layouts.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def _clean_size(self, field, min_size=None, max_size=None):
        """Clean a size field."""
        size = self.cleaned_data[field]
        if size is None:
            return None
        if is_percentage(size):
            # Calculate the percentage not counting the EFI parsation.
            size = calculate_size_from_percentage(
                self.boot_disk.size - EFI_PARsatION_SIZE, size
            )
        if min_size is not None and size < min_size:
            raise ValidationError(
                "Size is too small. Minimum size is %s." % min_size
            )
        if max_size is not None and size > max_size:
            raise ValidationError(
                "Size is too large. Maximum size is %s." % max_size
            )
        return size

3 View Complete Implementation : fields.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean(self, value):
        if value is None:
            return None
        else:
            ips = re.split(self.separators, value)
            ips = [ip.strip() for ip in ips if ip != ""]
            for ip in ips:
                try:
                    GenericIPAddressField().clean(ip, model_instance=None)
                except ValidationError:
                    raise ValidationError(
                        "Invalid IP address: %s; provide a list of "
                        "space-separated IP addresses" % ip
                    )
            return " ".join(ips)

3 View Complete Implementation : config_forms.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean_global_empty(self, value):
        """Make sure the value is not empty and is thus suitable to be
        feed to the sub fields' validators."""
        if not value or isinstance(value, (list, tuple)):
            # value is considered empty if it is in
            # validators.EMPTY_VALUES, or if each of the subvalues is
            # None.
            is_empty = value in validators.EMPTY_VALUES or all(
                v is None for v in value
            )
            if is_empty:
                if self.required:
                    raise ValidationError(self.error_messages["required"])
                else:
                    return None
            else:
                return True
        else:
            raise ValidationError(self.error_messages["invalid"])

3 View Complete Implementation : fields.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def to_python(self, value):
        if value is None or value == "":
            return None
        else:
            try:
                cidr = IPNetwork(value)
            except AddrFormatError:
                raise ValidationError(
                    "Invalid network: %(cidr)s", params={"cidr": value}
                )
            if cidr.cidr.version != 4:
                raise ValidationError(
                    "%(cidr)s: Only IPv4 networks supported.",
                    params={"cidr": value},
                )
        return str(cidr.cidr)

3 View Complete Implementation : fields.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean(self, value):
        if self.initial is None:
            if value is None:
                raise ValidationError("Must be given a value")
            # Create a new VersionedTextFile if one doesn't exist
            if isinstance(value, dict):
                return VersionedTextFile.objects.create(**value)
            else:
                return VersionedTextFile.objects.create(data=value)
        elif value is None:
            return self.initial
        else:
            # Create and return a new VersionedTextFile linked to the previous
            # VersionedTextFile
            if isinstance(value, dict):
                return self.initial.update(**value)
            else:
                return self.initial.update(value)

3 View Complete Implementation : bootsourceselection.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def delete(self, *args, **kwargs):
        commissioning_osystem = Config.objects.get_config(
            name="commissioning_osystem"
        )
        commissioning_series = Config.objects.get_config(
            name="commissioning_distro_series"
        )
        if (
            commissioning_osystem == self.os
            and commissioning_series == self.release
        ):
            raise ValidationError(
                "Unable to delete %s %s. "
                "It is the operating system used in ephemeral environments."
            )
        else:
            return super().delete(*args, **kwargs)

3 View Complete Implementation : filesystemgroup.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def _validate_lvm(self, filesystems=None):
        """Validate attached filesystems are correct type for LVM_VG.
        """
        if not self.is_lvm():
            return
        unique_fstypes = set(self._get_all_fstypes(filesystems=filesystems))
        if unique_fstypes != set([FILESYSTEM_TYPE.LVM_PV]):
            raise ValidationError(
                "Volume group can only contain lvm physical volumes."
            )

3 View Complete Implementation : bootsource.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean(self, *args, **kwargs):
        super(BootSource, self).clean(*args, **kwargs)

        # You have to specify one of {keyring_data, keyring_filename}.
        if len(self.keyring_filename) == 0 and len(self.keyring_data) == 0:
            raise ValidationError(
                "One of keyring_data or keyring_filename must be specified."
            )

        # You can have only one of {keyring_filename, keyring_data}; not
        # both.
        if len(self.keyring_filename) > 0 and len(self.keyring_data) > 0:
            raise ValidationError(
                "Only one of keyring_filename or keyring_data can be "
                "specified."
            )

3 View Complete Implementation : vlan.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean_dhcp_on(self):
        dhcp_on = self.cleaned_data.get("dhcp_on")
        if not dhcp_on:
            return dhcp_on
        for subnet in self.instance.subnet_set.all():
            if subnet.get_dynamic_ranges():
                return dhcp_on
        raise ValidationError(
            "dhcp can only be turned on when a dynamic IP range is defined."
        )

3 View Complete Implementation : filesystemgroup.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def add_device(self, device, fstype):
        """Adds a device to the array, creates the correct filesystem."""
        # Avoid circular import.
        from maasterver.models.filesystem import Filesystem

        if device.node != self.get_node():
            raise ValidationError(
                "Device needs to be from the same node as the rest of the "
                "array."
            )
        elif device.get_effective_filesystem() is not None:
            raise ValidationError(
                "There is another filesystem on this device."
            )
        else:
            Filesystem.objects.create(
                block_device=device, fstype=fstype, filesystem_group=self
            )
        return self

3 View Complete Implementation : machine.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def create_physical(self, params):
        """Create physical interface."""
        node = self._get_node_or_permission_error(
            params, permission=self._meta.edit_permission
        )
        form = PhysicalInterfaceForm(node=node, data=params)
        if form.is_valid():
            interface = form.save()
            self._update_obj_tags(interface, params)
            self._create_link_on_interface(interface, params)
        else:
            raise ValidationError(form.errors)

3 View Complete Implementation : packagerepository.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean_components(self):
        values = []
        for value in self.cleaned_data.get("components", []):
            values.extend([s.strip() for s in value.split(",")])
        if self.instance is not None and self.instance.default and values:
            raise ValidationError(
                "This is a default Ubuntu repository. Please update "
                "'disabled_components' instead."
            )
        return values

3 View Complete Implementation : scriptset.py
Copyright GNU Affero General Public License v3.0
Author : maas
def translate_result_type(result_type):
    if isinstance(result_type, int) or result_type.isdigit():
        ret = int(result_type)
        for result_type_id, _ in RESULT_TYPE_CHOICES:
            if ret == result_type_id:
                return ret
        raise ValidationError("Invalid result type numeric value.")
    elif result_type in ["test", "testing"]:
        return RESULT_TYPE.TESTING
    elif result_type in ["commission", "commissioning"]:
        return RESULT_TYPE.COMMISSIONING
    elif result_type in ["install", "installation"]:
        return RESULT_TYPE.INSTALLATION
    else:
        raise ValidationError(
            "Result type must be commissioning, testing, or installation."
        )

3 View Complete Implementation : machine.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def create_bond(self, params):
        """Create bond interface."""
        node = self._get_node_or_permission_error(
            params, permission=self._meta.edit_permission
        )
        form = BondInterfaceForm(node=node, data=params)
        if form.is_valid():
            interface = form.save()
            self._update_obj_tags(interface, params)
            self._create_link_on_interface(interface, params)
        else:
            raise ValidationError(form.errors)

3 View Complete Implementation : machine.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def update_interface(self, params):
        """Update the interface."""
        node = self._get_node_or_permission_error(
            params, permission=self._meta.edit_permission
        )
        interface = Interface.objects.get(node=node, id=params["interface_id"])
        if node.status == NODE_STATUS.DEPLOYED:
            interface_form = DeployedInterfaceForm
        else:
            interface_form = InterfaceForm.get_interface_form(interface.type)
        form = interface_form(instance=interface, data=params)
        if form.is_valid():
            interface = form.save()
            self._update_obj_tags(interface, params)
        else:
            raise ValidationError(form.errors)
        if "mode" in params:
            self.link_subnet(params)
        return self.full_dehydrate(node)

3 View Complete Implementation : filesystemgroup.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def get_virtual_block_device_block_size(self):
        """Return the block size that should be used on a created
        `VirtualBlockDevice` for this filesystem group."""
        if self.is_lvm():
            # Default for logical volume in LVM is 4096.
            return 4096
        elif self.is_raid():
            # mdadm by default creates raid devices with 512 block size.
            return 512
        elif self.is_bcache():
            # Bcache uses the block_size of the backing device.
            return self.get_bcache_backing_filesystem().get_block_size()
        elif self.is_vmfs():
            # By default VMFS uses a 1MB block size.
            return 1024
        else:
            raise ValidationError("Unknown group_type.")

3 View Complete Implementation : storage_layouts.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean(self):
        """Validate the data."""
        cleaned_data = super(StorageLayoutBase, self).clean()
        if len(self.block_devices) == 0:
            raise StorageLayoutMissingBootDiskError(
                "Node doesn't have any storage devices to configure."
            )
        disk_size = self.boot_disk.size
        total_size = EFI_PARsatION_SIZE + self.get_boot_size()
        root_size = self.get_root_size()
        if root_size is not None and total_size + root_size > disk_size:
            raise ValidationError(
                "Size of the boot parsation and root parsation are larger "
                "than the available space on the boot disk."
            )
        return cleaned_data

3 View Complete Implementation : machine.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def _create_link_on_interface(self, interface, params):
        """Create a link on a new interface."""
        mode = params.get("mode", None)
        subnet_id = params.get("subnet", None)
        if mode is not None:
            if mode != INTERFACE_LINK_TYPE.LINK_UP:
                link_form = InterfaceLinkForm(instance=interface, data=params)
                if link_form.is_valid():
                    link_form.save()
                else:
                    raise ValidationError(link_form.errors)
            elif subnet_id is not None:
                link_ip = interface.ip_addresses.get(
                    alloc_type=IPADDRESS_TYPE.STICKY, ip__isnull=True
                )
                link_ip.subnet = Subnet.objects.get(id=subnet_id)
                link_ip.save()

3 View Complete Implementation : blockdevice.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def delete(self):
        """Delete the block device.

        If this block device is part of a filesystem group then it cannot be
        deleted.
        """
        filesystem = self.get_effective_filesystem()
        if filesystem is not None:
            filesystem_group = filesystem.filesystem_group
            if filesystem_group is not None:
                raise ValidationError(
                    "Cannot delete block device because its part of "
                    "a %s." % filesystem_group.get_nice_name()
                )
        super(BlockDevice, self).delete()

3 View Complete Implementation : test_middleware.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_reports_ValidationError_as_Bad_Request(self):
        error_message = factory.make_string()
        exception = ValidationError(error_message)
        request = self.make_fake_request()
        response = self.process_exception(request, exception)
        self.astertIsInstance(response.content, bytes)
        self.astertEqual(
            (http.client.BAD_REQUEST, error_message),
            (
                response.status_code,
                response.content.decode(settings.DEFAULT_CHARSET),
            ),
        )

3 View Complete Implementation : fabric.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean_name(self):
        reserved = re.compile(r"^fabric-\d+$")
        if self.name is not None and self.name != "":
            if reserved.search(self.name):
                if self.id is None or self.name != "fabric-%d" % self.id:
                    raise ValidationError({"name": ["Reserved fabric name."]})
        elif self.id is not None:
            # Since we are not creating the fabric, force the (null or empty)
            # name to be the default name.
            self.name = "fabric-%d" % self.id

3 View Complete Implementation : domain.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def create_dnsdata(self, params):
        domain = self._get_domain_or_permission_error(params)
        dnsresource, _ = DNSResource.objects.get_or_create(
            domain=domain, name=params["name"]
        )
        params["dnsresource"] = dnsresource.id
        form = DNSDataForm(data=params)
        if form.is_valid():
            form.save()
        else:
            raise ValidationError(form.errors)

3 View Complete Implementation : interface.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean_vlan(self):
        created = self.instance.id is None
        new_vlan = self.cleaned_data.get("vlan")
        vlan_was_set = "vlan" in self.data
        if (created and new_vlan is None) or (
            not created and new_vlan is None and vlan_was_set
        ):
            raise ValidationError(
                "A VLAN interface must be connected to a tagged VLAN."
            )
        if new_vlan and new_vlan.vid == 0:
            raise ValidationError(
                "A VLAN interface can only belong to a tagged VLAN."
            )
        return new_vlan

3 View Complete Implementation : fannetwork.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def clean_host_reserve(self):
        if self.overlay is None or self.overlay == "":
            return
        if self.underlay is None or self.underlay == "":
            return
        overlay_prefix = IPNetwork(self.overlay).prefixlen
        underlay_prefix = IPNetwork(self.underlay).prefixlen
        slice_bits = underlay_prefix - overlay_prefix
        if self.host_reserve < 1:
            raise ValidationError({"host_reserve": ["Minimum value is 1"]})
        # The docs talk about 250 being the max host_reserve for a /8 slice.
        if self.host_reserve > (1 << slice_bits) - 6:
            raise ValidationError(
                {
                    "host_reserve": [
                        "Value is too large for the overlay network."
                    ]
                }
            )

3 View Complete Implementation : filesystemgroup.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def get_name_prefix(self):
        """Return the prefix that should be used when setting the name of
        this FilesystemGroup."""
        if self.is_lvm():
            return "vg"
        elif self.is_raid():
            return "md"
        elif self.is_bcache():
            return "bcache"
        elif self.is_vmfs():
            return "vmfs"
        else:
            raise ValidationError("Unknown group_type.")

3 View Complete Implementation : subnet.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def validate_gateway_ip(self):
        if self.gateway_ip is None or self.gateway_ip == "":
            return
        gateway_addr = IPAddress(self.gateway_ip)
        network = self.get_ipnetwork()
        if gateway_addr in network:
            # If the gateway is in the network, it is fine.
            return
        elif network.version == 6 and gateway_addr.is_link_local():
            # If this is an IPv6 network and the gateway is in the link-local
            # network (fe80::/64 -- required to be configured by the spec),
            # then it is also valid.
            return
        else:
            # The gateway is not valid for the network.
            message = "Gateway IP must be within CIDR range."
            raise ValidationError({"gateway_ip": [message]})

3 View Complete Implementation : node_constraint_filter_forms.py
Copyright GNU Affero General Public License v3.0
Author : maas
def interfaces_validator(constraint_map):
    """Validate the given LabeledConstraintMap object."""
    # At this point, the basic syntax of a labeled constraint map will have
    # already been validated by the underlying form field. However, we also
    # need to validate the specified things we're looking for in the
    # interfaces domain.
    for label in constraint_map:
        constraints = constraint_map[label]
        for constraint_name in constraints:
            if constraint_name not in NETWORKING_CONSTRAINT_NAMES:
                raise ValidationError(
                    "Unknown interfaces constraint: '%s" % constraint_name
                )

1 2 3