def _clean_dns_servers(self, cleaned_data): dns_servers = cleaned_data.get("dns_servers", None) if dns_servers is None: return cleaned_data clean_dns_servers = [] for dns_server in dns_servers: ip_list_form = IPListFormField() ip_list_cleaned = ip_list_form.clean(dns_server) if ip_list_cleaned is not None: clean_dns_servers += ip_list_cleaned.split(" ") cleaned_data["dns_servers"] = clean_dns_servers return cleaned_data
class DomainForm(MAASModelForm): """Domain creation/edition form.""" class Meta: model = Domain fields = ("name", "authoritative", "ttl") ttl = forms.IntegerField(min_value=1, max_value=604800, required=False) authoritative = forms.NullBooleanField(required=False) forward_dns_servers = IPListFormField(required=False) def save(self): super(MAASModelForm, self).save() fwd_srvrs = self.cleaned_data.get("forward_dns_servers") if fwd_srvrs is not None: fwd_srvrs_list = fwd_srvrs.split(" ") for fwd_srvr_ip in fwd_srvrs_list: fwd_srvr = ForwardDNSServer.objects.get_or_create( ip_address=fwd_srvr_ip)[0] fwd_srvr.domains.add(self.instance) fwd_srvr.save() del self.cleaned_data["forward_dns_servers"] return self.instance def clean(self): if self.data.get("authoritative") and len( self.data.get("forward_dns_servers", "")): raise ValidationError( "a domain cannot be both authoritative and have forward dns servers" ) super(DomainForm, self).clean() def _post_clean(self): # ttl=None needs to make it through. See also APIEditMixin self.cleaned_data = { key: value for key, value in self.cleaned_data.items() if value is not None or key == "ttl" } super(APIEditMixin, self)._post_clean()
def test_rejects_invalid_input(self): invalid = factory.make_name("invalid") input = " ".join([factory.make_ip_address(), invalid]) error = self.assertRaises(ValidationError, IPListFormField().clean, input) self.assertIn("Invalid IP address: %s" % invalid, error.message)
def test_accepts_comma_separated_ips(self): ips = [factory.make_ip_address() for _ in range(5)] input = ",".join(ips) self.assertEqual(" ".join(ips), IPListFormField().clean(input))
def test_accepts_single_ip(self): ip = factory.make_ip_address() self.assertEqual(ip, IPListFormField().clean(ip))
def test_accepts_none(self): self.assertIsNone(IPListFormField().clean(None))