mixins.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from django.utils import timezone
  2. from django.utils.translation import ungettext_lazy, ugettext_lazy as _
  3. import floppyforms as forms
  4. from misago.conf import settings
  5. from misago.utils.strings import slugify
  6. class FloodProtectionMixin(object):
  7. def clean(self):
  8. cleaned_data = super(FloodProtectionMixin, self).clean()
  9. if self.request.block_flood_requests and self.request.user.last_post:
  10. diff = timezone.now() - self.request.user.last_post
  11. diff = diff.seconds + (diff.days * 86400)
  12. wait_for = settings.FLOOD_DELAY - diff
  13. if wait_for > 0:
  14. if wait_for < 5:
  15. raise forms.ValidationError(_("You can't post one message so quickly after another. Please wait a moment and try again."))
  16. else:
  17. raise forms.ValidationError(ungettext_lazy(
  18. "You can't post one message so quickly after another. Please wait %(seconds)d second and try again.",
  19. "You can't post one message so quickly after another. Please wait %(seconds)d seconds and try again.",
  20. wait_for) % {
  21. 'seconds': wait_for,
  22. })
  23. return cleaned_data
  24. class ValidateThreadNameMixin(object):
  25. def clean_thread_name(self):
  26. data = self.cleaned_data['thread_name']
  27. slug = slugify(data)
  28. if len(slug) < settings.thread_name_min:
  29. raise forms.ValidationError(ungettext_lazy(
  30. "Thread name must contain at least one alpha-numeric character.",
  31. "Thread name must contain at least %(count)d alpha-numeric characters.",
  32. settings.thread_name_min
  33. ) % {'count': settings.thread_name_min})
  34. if len(data) > settings.thread_name_max:
  35. raise forms.ValidationError(ungettext_lazy(
  36. "Thread name cannot be longer than %(count)d character.",
  37. "Thread name cannot be longer than %(count)d characters.",
  38. settings.thread_name_max
  39. ) % {'count': settings.thread_name_max})
  40. return data
  41. class ValidatePostLengthMixin(object):
  42. def clean_post(self):
  43. data = self.cleaned_data['post']
  44. if len(data) < settings.post_length_min:
  45. raise forms.ValidationError(ungettext_lazy(
  46. "Post content cannot be empty.",
  47. "Post content cannot be shorter than %(count)d characters.",
  48. settings.post_length_min
  49. ) % {'count': settings.post_length_min})
  50. return data