You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

forms.py 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from django import forms
  2. from django.conf import settings
  3. from django.contrib.flatpages.models import FlatPage
  4. from django.utils.translation import gettext, gettext_lazy as _
  5. class FlatpageForm(forms.ModelForm):
  6. url = forms.RegexField(
  7. label=_("URL"),
  8. max_length=100,
  9. regex=r'^[-\w/\.~]+$',
  10. help_text=_("Example: '/about/contact/'. Make sure to have leading and trailing slashes."),
  11. error_messages={
  12. "invalid": _(
  13. "This value must contain only letters, numbers, dots, "
  14. "underscores, dashes, slashes or tildes."
  15. ),
  16. },
  17. )
  18. class Meta:
  19. model = FlatPage
  20. fields = '__all__'
  21. def __init__(self, *args, **kwargs):
  22. super().__init__(*args, **kwargs)
  23. if not self._trailing_slash_required():
  24. self.fields['url'].help_text = _(
  25. "Example: '/about/contact'. Make sure to have a leading slash."
  26. )
  27. def _trailing_slash_required(self):
  28. return (
  29. settings.APPEND_SLASH and
  30. 'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE
  31. )
  32. def clean_url(self):
  33. url = self.cleaned_data['url']
  34. if not url.startswith('/'):
  35. raise forms.ValidationError(
  36. gettext("URL is missing a leading slash."),
  37. code='missing_leading_slash',
  38. )
  39. if self._trailing_slash_required() and not url.endswith('/'):
  40. raise forms.ValidationError(
  41. gettext("URL is missing a trailing slash."),
  42. code='missing_trailing_slash',
  43. )
  44. return url
  45. def clean(self):
  46. url = self.cleaned_data.get('url')
  47. sites = self.cleaned_data.get('sites')
  48. same_url = FlatPage.objects.filter(url=url)
  49. if self.instance.pk:
  50. same_url = same_url.exclude(pk=self.instance.pk)
  51. if sites and same_url.filter(sites__in=sites).exists():
  52. for site in sites:
  53. if same_url.filter(sites=site).exists():
  54. raise forms.ValidationError(
  55. _('Flatpage with url %(url)s already exists for site %(site)s'),
  56. code='duplicate_url',
  57. params={'url': url, 'site': site},
  58. )
  59. return super().clean()