2015-02-25 17:29:39 +00:00
|
|
|
from django import forms
|
|
|
|
from django.core.exceptions import ValidationError
|
2015-03-10 21:51:10 +00:00
|
|
|
|
2015-03-10 22:27:32 +00:00
|
|
|
from .validators import validate_domain_protocol
|
2015-02-25 17:29:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
class WebsiteAdminForm(forms.ModelForm):
|
|
|
|
def clean(self):
|
2015-03-10 21:51:10 +00:00
|
|
|
""" Prevent multiples domains on the same protocol """
|
2015-02-25 17:29:39 +00:00
|
|
|
domains = self.cleaned_data.get('domains')
|
2015-03-10 21:51:10 +00:00
|
|
|
if not domains:
|
|
|
|
return self.cleaned_data
|
|
|
|
protocol = self.cleaned_data.get('protocol')
|
2015-02-25 17:29:39 +00:00
|
|
|
for domain in domains.all():
|
2015-03-10 22:27:32 +00:00
|
|
|
try:
|
|
|
|
validate_domain_protocol(self.instance, domain, protocol)
|
|
|
|
except ValidationError as e:
|
|
|
|
# TODO not sure about this one
|
|
|
|
self.add_error(None, e)
|
2015-02-25 17:29:39 +00:00
|
|
|
return self.cleaned_data
|
|
|
|
|
2015-03-25 15:45:04 +00:00
|
|
|
|
|
|
|
class WebsiteDirectiveInlineFormSet(forms.models.BaseInlineFormSet):
|
|
|
|
""" Validate uniqueness """
|
|
|
|
def clean(self):
|
|
|
|
values = {}
|
|
|
|
for form in self.forms:
|
|
|
|
name = form.cleaned_data.get('name', None)
|
|
|
|
if name is not None:
|
|
|
|
directive = form.instance.directive_class
|
|
|
|
if directive.unique_name and name in values:
|
|
|
|
form.add_error(None, ValidationError(
|
|
|
|
_("Only one %s can be defined.") % directive.get_verbose_name()
|
|
|
|
))
|
|
|
|
value = form.cleaned_data.get('value', None)
|
|
|
|
if value is not None:
|
|
|
|
if directive.unique_value and value in values.get(name, []):
|
|
|
|
form.add_error('value', ValidationError(
|
|
|
|
_("This value is already used by other %s.") % unicode(directive.get_verbose_name())
|
|
|
|
))
|
|
|
|
try:
|
|
|
|
values[name].append(value)
|
|
|
|
except KeyError:
|
|
|
|
values[name] = [value]
|