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
|
2017-01-27 03:58:33 +08:00
|
|
|
from django.utils.translation import gettext, gettext_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):
|
2016-02-06 02:53:03 +08:00
|
|
|
url = forms.RegexField(
|
|
|
|
label=_("URL"),
|
|
|
|
max_length=100,
|
|
|
|
regex=r'^[-\w/\.~]+$',
|
|
|
|
help_text=_("Example: '/about/contact/'. Make sure to have leading and trailing slashes."),
|
2014-08-03 06:33:18 +08:00
|
|
|
error_messages={
|
2016-02-06 02:53:03 +08:00
|
|
|
"invalid": _(
|
|
|
|
"This value must contain only letters, numbers, dots, "
|
|
|
|
"underscores, dashes, slashes or tildes."
|
|
|
|
),
|
2014-08-03 06:33:18 +08:00
|
|
|
},
|
|
|
|
)
|
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(
|
2017-01-27 03:58:33 +08:00
|
|
|
gettext("URL is missing a leading slash."),
|
2013-06-06 02:55:05 +08:00
|
|
|
code='missing_leading_slash',
|
|
|
|
)
|
2017-01-01 02:24:00 +08:00
|
|
|
if (settings.APPEND_SLASH and
|
|
|
|
'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE and
|
2013-11-26 17:43:46 +08:00
|
|
|
not url.endswith('/')):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise forms.ValidationError(
|
2017-01-27 03:58:33 +08:00
|
|
|
gettext("URL is missing a trailing slash."),
|
2013-06-06 02:55:05 +08:00
|
|
|
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
|
|
|
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().clean()
|