gva/gnuviechadmin/domains/forms.py
Jan Dittberner 7c9509c159 implement domain name validation
- implement domains.forms.relative_domain_validator
- use the validator for domain field validation in
  domains.forms.CreateHostingDomainForm
- use the validator for subdomain field validation in
  websites.forms.AddWebsiteForm
2015-01-27 16:41:44 +01:00

66 lines
1.9 KiB
Python

"""
This module defines form classes for domain editing.
"""
from __future__ import absolute_import, unicode_literals
import re
from django import forms
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from crispy_forms.helper import FormHelper
from crispy_forms.layout import (
Layout,
Submit,
)
from .models import HostingDomain
def relative_domain_validator(value):
"""
This validator ensures that the given value is a valid lowercase
"""
if len(value) > 254:
raise forms.ValidationError(
_('host name too long'), code='too-long')
allowed = re.compile(r"(?!-)[a-z\d-]{1,63}(?<!-)$")
if not all(allowed.match(x) for x in value.split('.')):
raise forms.ValidationError(_('invalid domain name'))
class CreateHostingDomainForm(forms.ModelForm):
"""
This form is used to create new HostingDomain instances.
"""
class Meta:
model = HostingDomain
fields = ['domain']
def __init__(self, instance, *args, **kwargs):
self.hosting_package = kwargs.pop('hostingpackage')
super(CreateHostingDomainForm, self).__init__(*args, **kwargs)
self.fields['domain'].validators.append(relative_domain_validator)
self.helper = FormHelper()
self.helper.form_action = reverse(
'create_hosting_domain', kwargs={
'package': self.hosting_package.id
})
self.helper.layout = Layout(
'domain',
Submit('submit', _('Add Hosting Domain')),
)
def clean(self):
self.cleaned_data = super(CreateHostingDomainForm, self).clean()
self.cleaned_data['hosting_package'] = self.hosting_package
def save(self, commit=True):
return HostingDomain.objects.create_for_hosting_package(
commit=commit, **self.cleaned_data)
def save_m2m(self):
pass