Permalink
Browse files

Merge pull request #9 from sergiocharpineljr/bug_526469

526469: No field for enableURL
  • Loading branch information...
2 parents 5f16017 + f722df7 commit 09b65b19d199efbfa096abb5dab67abbe42d5792 @bwinton bwinton committed Aug 17, 2012
View
@@ -12,6 +12,8 @@
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import get_language_info
+from django.utils.functional import curry
+from django.utils.translation.trans_real import parse_accept_lang_header
import ispdb.audit as audit
class Domain(models.Model):
@@ -187,27 +189,58 @@ class Issue(models.Model):
status = models.CharField(max_length=20, choices=STATUS_CHOICES,
default="open")
-class DocURL(models.Model):
+
+class CommonConfigURL(models.Model):
url = models.URLField(
- verbose_name="URL of the page describing these settings")
- config = models.ForeignKey(Config)
+ verbose_name="URL of the page")
+ config = models.ForeignKey(Config, related_name="%(class)s_set")
+
+ class Meta:
+ abstract = True
def __str__(self): return str(self.url)
def __unicode__(self): return self.url
-class DocURLDesc(models.Model):
+
+class CommonURLDesc(models.Model):
description = models.TextField(
max_length=100,
- verbose_name="Description of the settings page")
+ verbose_name="Description")
language = models.CharField(
max_length=10,
verbose_name="Language",
choices=settings.LANGUAGES)
- docurl = models.ForeignKey(DocURL, related_name="descriptions")
+
+ class Meta:
+ abstract = True
def __str__(self): return str(self.description)
def __unicode__(self): return self.description
+
+class DocURL(CommonConfigURL):
+ pass
+DocURL._meta.get_field('url').verbose_name = ("URL of the page describing "
+ "these settings")
+
+
+class DocURLDesc(CommonURLDesc):
+ docurl = models.ForeignKey(DocURL, related_name="descriptions")
+DocURLDesc._meta.get_field('description').verbose_name = ('Description of the '
+ 'settings page')
+
+
+class EnableURL(CommonConfigURL):
+ pass
+EnableURL._meta.get_field('url').verbose_name = ("URL of the page with enable "
+ "instructions")
+
+
+class EnableURLInst(CommonURLDesc):
+ enableurl = models.ForeignKey(EnableURL, related_name="instructions")
+EnableURLInst._meta.get_field('description').verbose_name = ('Instruction')
+
+
# Forms
def clean_port(self,field):
data = self.cleaned_data[field]
@@ -247,6 +280,18 @@ def clean(self, **kwargs):
self.errors.clear()
return cleaned_data
+ def save(self, commit=True):
+ super(DynamicModelForm, self).save(commit=False)
+ if commit:
+ # delete if exists
+ if self.cleaned_data and self.cleaned_data['DELETE']:
+ if self.instance.pk:
+ return self.instance.delete()
+ else:
+ return None
+ super(DynamicModelForm, self).save()
+ return self.instance
+
class DynamicBaseModelFormSet(BaseModelFormSet):
"""
@@ -287,36 +332,39 @@ class Meta:
fields = ['title', 'description']
-class DocURLDescForm(DynamicModelForm):
- class Meta:
- model = DocURLDesc
- exclude = ['docurl']
-
+class LanguageDescModelForm(DynamicModelForm):
+ """
+ A DynamicModelForm for classes with a language and a description fields
+ """
def __init__(self, *args, **kwargs):
- super(DocURLDescForm, self).__init__(*args, **kwargs)
- self.fields['description'].widget.attrs.update({'rows': 2, 'cols': 20})
+ http_accept_language = kwargs.pop('http_accept_language', '')
+ super(LanguageDescModelForm, self).__init__(*args, **kwargs)
+ self.fields['description'].widget.attrs.update({'rows': 1, 'cols': 20})
+ choices = []
+ # add HTTP_ACCEPTED_LANG first
+ if http_accept_language:
+ for code, q in parse_accept_lang_header(http_accept_language):
+ try:
+ li = get_language_info(code)
+ except:
+ continue
+ choices.append((code, li['name'] + ' - ' + li['name_local']))
# Redefine our choices, so we can add the translated language names and
# sort the list by language name
- choices = []
choices.append(self.fields['language'].choices[0])
langs = self.fields['language'].choices[1:]
langs.sort(key=lambda l: l[1].lower())
for code, lang in langs:
li = get_language_info(code)
choices.append((code, lang + ' - ' + li['name_local']))
self.fields['language'].choices = choices
+ self.fields['language'].initial = choices[0]
- def save(self, commit=True):
- super(DocURLDescForm, self).save(commit=False)
- if commit:
- # delete if exists
- if self.cleaned_data and self.cleaned_data['DELETE']:
- if self.instance.pk:
- return self.instance.delete()
- else:
- return None
- super(DocURLDescForm, self).save()
- return self.instance
+
+class DocURLDescForm(LanguageDescModelForm):
+ class Meta:
+ model = DocURLDesc
+ exclude = ['docurl']
class BaseDocURLDescFormSet(DynamicBaseModelFormSet):
@@ -383,11 +431,17 @@ class BaseDocURLFormSet(DynamicBaseModelFormSet):
def __init__(self, *args, **kwargs):
kwargs['prefix'] = 'docurl'
+ # get request.META to add HTTP_ACCEPT_LANGUAGE on top of languages
+ # choices
+ meta = kwargs.pop('meta', {})
+ accept_lang = meta.get('HTTP_ACCEPT_LANGUAGE', '')
super(BaseDocURLFormSet, self).__init__(*args, **kwargs)
# construct description formsets
self.DocURLDescFormSet = modelformset_factory(DocURLDesc,
extra=self.extra, form=DocURLDescForm,
formset=BaseDocURLDescFormSet)
+ self.DocURLDescFormSet.form = staticmethod(curry(DocURLDescForm,
+ http_accept_language=accept_lang))
for index, form in enumerate(self.forms):
prefix = 'desc_%s' % index
data = self.data or None
@@ -437,6 +491,138 @@ def delete(self):
desc.instance.delete()
form.instance.delete()
+
+class EnableURLInstForm(LanguageDescModelForm):
+ class Meta:
+ model = EnableURLInst
+ exclude = ['enableurl']
+
+
+class BaseEnableURLInstFormSet(DynamicBaseModelFormSet):
+ model = EnableURLInst
+
+ def __init__(self, *args, **kwargs):
+ self.enableurl_delete = kwargs.pop('delete', False)
+ super(BaseEnableURLInstFormSet, self).__init__(*args, **kwargs)
+ # if enableurl is deleted, set required to false so they don't
+ # need to be filled
+ if self.enableurl_delete:
+ for form in self.forms:
+ for k, field in form.fields.iteritems():
+ field.required = False
+
+ def clean(self, **kwargs):
+ super(BaseEnableURLInstFormSet, self).clean(**kwargs)
+ if any(self.errors):
+ return
+ deleted_forms = 0
+ languages = []
+ for i in range(0, self.total_form_count()):
+ form = self.forms[i]
+ if (not form.cleaned_data) or form.cleaned_data['DELETE']:
+ deleted_forms += 1
+ continue
+ # Check for repeated languages
+ if form.cleaned_data['language'] in languages:
+ raise ValidationError("Duplicated language found.")
+ if form.cleaned_data['language'] != "Other":
+ languages.append(form.cleaned_data['language'])
+ # Check if all forms are deleted
+ if (not self.enableurl_delete) and (self.total_form_count() == 0 or
+ self.total_form_count() == deleted_forms):
+ raise ValidationError("At least one instruction should be "
+ "specified.")
+
+
+class EnableURLForm(DynamicModelForm):
+ class Meta:
+ model = EnableURL
+ fields = ['url']
+
+ def save(self, commit=True):
+ m = super(EnableURLForm, self).save(commit=False)
+ self.inst_formset.save(commit=False)
+ if commit:
+ if self.cleaned_data and self.cleaned_data['DELETE']:
+ # delete enableurl and instruction forms
+ if self.instance.pk:
+ for form in self.inst_formset:
+ if form.instance.pk:
+ form.instance.delete()
+ self.instance.delete()
+ return None
+ m = super(EnableURLForm, self).save()
+ for form in self.inst_formset:
+ form.instance.enableurl = m
+ self.inst_formset.save()
+ return m
+
+class BaseEnableURLFormSet(DynamicBaseModelFormSet):
+ model = EnableURL
+
+ def __init__(self, *args, **kwargs):
+ kwargs['prefix'] = 'enableurl'
+ # get request.META to add HTTP_ACCEPT_LANGUAGE on top of languages
+ # choices
+ meta = kwargs.pop('meta', {})
+ accept_lang = meta.get('HTTP_ACCEPT_LANGUAGE', '')
+ super(BaseEnableURLFormSet, self).__init__(*args, **kwargs)
+ # construct instructions formsets
+ self.EnableURLInstFormSet = modelformset_factory(EnableURLInst,
+ extra=self.extra, form=EnableURLInstForm,
+ formset=BaseEnableURLInstFormSet)
+ self.EnableURLInstFormSet.form = staticmethod(curry(EnableURLInstForm,
+ http_accept_language=accept_lang))
+ for index, form in enumerate(self.forms):
+ prefix = 'inst_%s' % index
+ data = self.data or None
+ delete = False
+ if self.queryset:
+ qs = EnableURLInst.objects.filter(enableurl=form.instance)
+ else:
+ qs = EnableURLInst.objects.none()
+ # if form is deleted, delete the instructions
+ if (self.data and
+ self.data.get(form.prefix+'-DELETE', '') == "True"):
+ delete = True
+ form.inst_formset = self.EnableURLInstFormSet(data=data,
+ prefix=prefix,
+ delete=delete,
+ queryset=qs)
+ # create a empty_desc_form
+ if self.forms:
+ self.empty_desc_form = self.forms[0].inst_formset.empty_form
+ else:
+ formset = self.EnableURLInstFormSet()
+ self.empty_desc_form = formset.empty_form
+
+ def clean(self, **kwargs):
+ super(BaseEnableURLFormSet, self).clean(**kwargs)
+ if any(self.errors):
+ return
+ urls = []
+ for i in range(0, self.total_form_count()):
+ form = self.forms[i]
+ if (not form.cleaned_data) or form.cleaned_data['DELETE']:
+ continue
+ # Check for repeated urls
+ if form.cleaned_data['url'] in urls:
+ raise ValidationError("Duplicated URL found.")
+ urls.append(form.cleaned_data['url'])
+
+ def is_valid(self, *args, **kwargs):
+ result = super(BaseEnableURLFormSet, self).is_valid(*args, **kwargs)
+ for form in self.forms:
+ result = result and form.inst_formset.is_valid()
+ return result
+
+ def delete(self):
+ for form in self.forms:
+ for inst in form.inst_formset:
+ inst.instance.delete()
+ form.instance.delete()
+
+
class DomainForm(DynamicModelForm):
class Meta:
fields = ('name',)
@@ -560,10 +746,13 @@ class Meta:
def __init__(self, *args, **kwargs):
self.domain_formset = kwargs.pop('domain_formset', None)
self.docurl_formset = kwargs.pop('docurl_formset', None)
+ self.enableurl_formset = kwargs.pop('enableurl_formset', None)
if not self.domain_formset:
raise(Exception('Domain formset required.'))
if not self.docurl_formset:
raise(Exception('DocURL formset required.'))
+ if not self.enableurl_formset:
+ raise(Exception('EnableURL formset required.'))
super(ConfigForm, self).__init__(*args, **kwargs)
def clean_incoming_port(self):
@@ -575,7 +764,8 @@ def clean_outgoing_port(self):
def is_valid_all(self, *args, **kwargs):
return (self.is_valid(*args, **kwargs) and
self.domain_formset.is_valid(*args, **kwargs) and
- self.docurl_formset.is_valid(*args, **kwargs))
+ self.docurl_formset.is_valid(*args, **kwargs) and
+ self.enableurl_formset.is_valid(*args, **kwargs))
def save_all(self, *args, **kwargs):
super(ConfigForm, self).save(*args, **kwargs)
@@ -589,3 +779,8 @@ def save_all(self, *args, **kwargs):
for form in self.docurl_formset:
form.instance.config = self.instance
self.docurl_formset.save()
+ # Save EnableURL formset
+ self.enableurl_formset.save(commit=False)
+ for form in self.enableurl_formset:
+ form.instance.config = self.instance
+ self.enableurl_formset.save()
@@ -69,6 +69,14 @@ def xmlOneDotOne(data):
text = unicode(text)
e.text = text
+ # EnableURL
+ for enableurl in data.enableurl_set.all():
+ enable = ET.SubElement(emailProvider, "enable")
+ enable.attrib["visiturl"] = enableurl.url
+ for inst in enableurl.instructions.all():
+ d = ET.SubElement(enable, "instruction")
+ d.attrib["lang"] = inst.language
+ d.text = unicode(inst.description)
# DocURL
for docurl in data.docurl_set.all():
doc = ET.SubElement(emailProvider, "documentation")
@@ -6,11 +6,6 @@
#domain_list table {
max-width: 40em;
}
-#add_domain {
- position: absolute;
- bottom: 1em;
- right: 1em;
-}
input[readonly=readonly] {
color: grey;
background-color:#F0F0F0;
@@ -33,15 +28,7 @@ input[readonly=readonly] {
}
table.tab_descs td, table.tab_descs th,
+table.tab_insts td, table.tab_insts th,
td.noborder, th.noborder {
border-bottom: 0px;
}
-
-.add_desc {
- font-size: 12px;
-}
-
-#add_docurl {
- padding-top: 10px;
- padding-bottom: 10px;
-}
Oops, something went wrong.

0 comments on commit 09b65b1

Please sign in to comment.