gva/gnuviechadmin/websites/forms.py

69 lines
2.1 KiB
Python
Raw Normal View History

"""
This module defines form classes for website editing.
"""
from __future__ import absolute_import, unicode_literals
from django import forms
from django.urls import reverse
from django.utils.translation import ugettext as _
from crispy_forms.bootstrap import AppendedText
from crispy_forms.helper import FormHelper
from crispy_forms.layout import (
Layout,
Submit,
)
from domains.forms import relative_domain_validator
from .models import Website
class AddWebsiteForm(forms.ModelForm):
"""
This form is used to create new Website instances.
"""
class Meta:
model = Website
fields = ['subdomain', 'wildcard']
def __init__(self, *args, **kwargs):
self.hosting_package = kwargs.pop('hostingpackage')
self.hosting_domain = kwargs.pop('domain')
super(AddWebsiteForm, self).__init__(*args, **kwargs)
self.fields['subdomain'].validators.append(relative_domain_validator)
if Website.objects.filter(
wildcard=True, domain=self.hosting_domain
).exists():
self.fields['wildcard'].widget = forms.HiddenInput()
self.helper = FormHelper()
self.helper.form_action = reverse(
'add_website', kwargs={
'package': self.hosting_package.id,
'domain': self.hosting_domain.domain,
}
)
self.helper.layout = Layout(
AppendedText('subdomain', '.' + self.hosting_domain.domain),
'wildcard',
Submit('submit', _('Add website')),
)
def clean_subdomain(self):
data = self.cleaned_data['subdomain']
if Website.objects.filter(
domain=self.hosting_domain, subdomain=data
).exists():
raise forms.ValidationError(
_('There is already a website for this subdomain'))
relative_domain_validator(
"{0}.{1}".format(data, self.hosting_domain.domain))
return data
def save(self, commit=True):
self.instance.domain = self.hosting_domain
self.instance.osuser = self.hosting_package.osuser
return super(AddWebsiteForm, self).save(commit)