2011-10-07 23:45:52 +08:00
|
|
|
from django import forms
|
2012-01-29 04:27:23 +08:00
|
|
|
from django.conf import settings
|
2011-10-07 23:45:52 +08:00
|
|
|
from django.contrib.flatpages.models import FlatPage
|
2012-01-29 04:27:23 +08:00
|
|
|
from django.utils.translation import ugettext, ugettext_lazy as _
|
2011-10-07 23:45:52 +08:00
|
|
|
|
2013-10-31 23:42:28 +08:00
|
|
|
|
2011-10-07 23:45:52 +08:00
|
|
|
class FlatpageForm(forms.ModelForm):
|
|
|
|
url = forms.RegexField(label=_("URL"), max_length=100, regex=r'^[-\w/\.~]+$',
|
2013-11-03 17:22:11 +08:00
|
|
|
help_text=_("Example: '/about/contact/'. Make sure to have leading"
|
|
|
|
" and trailing slashes."),
|
2014-08-03 06:33:18 +08:00
|
|
|
error_messages={
|
|
|
|
"invalid": _("This value must contain only letters, numbers,"
|
|
|
|
" dots, underscores, dashes, slashes or tildes."),
|
|
|
|
},
|
|
|
|
)
|
2011-10-07 23:45:52 +08:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = FlatPage
|
2013-02-22 05:56:55 +08:00
|
|
|
fields = '__all__'
|
2011-10-07 23:45:52 +08:00
|
|
|
|
2012-01-29 04:27:23 +08:00
|
|
|
def clean_url(self):
|
|
|
|
url = self.cleaned_data['url']
|
|
|
|
if not url.startswith('/'):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise forms.ValidationError(
|
|
|
|
ugettext("URL is missing a leading slash."),
|
|
|
|
code='missing_leading_slash',
|
|
|
|
)
|
2012-01-29 04:27:23 +08:00
|
|
|
if (settings.APPEND_SLASH and
|
2013-11-26 17:43:46 +08:00
|
|
|
'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLASSES and
|
|
|
|
not url.endswith('/')):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise forms.ValidationError(
|
|
|
|
ugettext("URL is missing a trailing slash."),
|
|
|
|
code='missing_trailing_slash',
|
|
|
|
)
|
2012-01-29 04:27:23 +08:00
|
|
|
return url
|
|
|
|
|
2011-10-07 23:45:52 +08:00
|
|
|
def clean(self):
|
2015-05-14 02:51:18 +08:00
|
|
|
url = self.cleaned_data.get('url')
|
|
|
|
sites = self.cleaned_data.get('sites')
|
2011-10-07 23:45:52 +08:00
|
|
|
|
2011-10-17 08:56:32 +08:00
|
|
|
same_url = FlatPage.objects.filter(url=url)
|
|
|
|
if self.instance.pk:
|
|
|
|
same_url = same_url.exclude(pk=self.instance.pk)
|
2011-10-07 23:45:52 +08:00
|
|
|
|
2012-04-29 07:44:14 +08:00
|
|
|
if sites and same_url.filter(sites__in=sites).exists():
|
2011-10-07 23:45:52 +08:00
|
|
|
for site in sites:
|
2011-10-17 08:56:32 +08:00
|
|
|
if same_url.filter(sites=site).exists():
|
2011-10-07 23:45:52 +08:00
|
|
|
raise forms.ValidationError(
|
2013-06-06 02:55:05 +08:00
|
|
|
_('Flatpage with url %(url)s already exists for site %(site)s'),
|
|
|
|
code='duplicate_url',
|
|
|
|
params={'url': url, 'site': site},
|
|
|
|
)
|
2011-10-07 23:45:52 +08:00
|
|
|
|
|
|
|
return super(FlatpageForm, self).clean()
|