Development of an internal social media platform with personalised dashboards for students
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.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 clean_url(self):
  22. url = self.cleaned_data['url']
  23. if not url.startswith('/'):
  24. raise forms.ValidationError(
  25. gettext("URL is missing a leading slash."),
  26. code='missing_leading_slash',
  27. )
  28. if (settings.APPEND_SLASH and
  29. 'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE and
  30. not url.endswith('/')):
  31. raise forms.ValidationError(
  32. gettext("URL is missing a trailing slash."),
  33. code='missing_trailing_slash',
  34. )
  35. return url
  36. def clean(self):
  37. url = self.cleaned_data.get('url')
  38. sites = self.cleaned_data.get('sites')
  39. same_url = FlatPage.objects.filter(url=url)
  40. if self.instance.pk:
  41. same_url = same_url.exclude(pk=self.instance.pk)
  42. if sites and same_url.filter(sites__in=sites).exists():
  43. for site in sites:
  44. if same_url.filter(sites=site).exists():
  45. raise forms.ValidationError(
  46. _('Flatpage with url %(url)s already exists for site %(site)s'),
  47. code='duplicate_url',
  48. params={'url': url, 'site': site},
  49. )
  50. return super().clean()