mixins.py 3.0 KB

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