forms.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. from django import forms
  2. from django.utils.translation import ungettext, ugettext_lazy as _
  3. from mptt.forms import TreeNodeChoiceField
  4. from misago.forms import Form
  5. from misago.forums.models import Forum
  6. from misago.utils import slugify
  7. from misago.utils.validators import validate_sluggable
  8. class ThreadNameMixin(object):
  9. def clean_thread_name(self):
  10. data = self.cleaned_data['thread_name']
  11. slug = slugify(data)
  12. if len(slug) < self.request.settings['thread_name_min']:
  13. raise forms.ValidationError(ungettext(
  14. "Thread name must contain at least one alpha-numeric character.",
  15. "Thread name must contain at least %(count)d alpha-numeric characters.",
  16. self.request.settings['thread_name_min']
  17. ) % {'count': self.request.settings['thread_name_min']})
  18. if len(data) > self.request.settings['thread_name_max']:
  19. raise forms.ValidationError(ungettext(
  20. "Thread name cannot be longer than %(count)d character.",
  21. "Thread name cannot be longer than %(count)d characters.",
  22. self.request.settings['thread_name_max']
  23. ) % {'count': self.request.settings['thread_name_max']})
  24. return data
  25. class PostForm(Form, ThreadNameMixin):
  26. post = forms.CharField(widget=forms.Textarea)
  27. def __init__(self, data=None, file=None, request=None, mode=None, *args, **kwargs):
  28. self.mode = mode
  29. super(PostForm, self).__init__(data, file, request=request, *args, **kwargs)
  30. def finalize_form(self):
  31. self.layout = [
  32. [
  33. None,
  34. [
  35. ('thread_name', {'label': _("Thread Name")}),
  36. ('post', {'label': _("Post Content")}),
  37. ],
  38. ],
  39. ]
  40. if self.mode not in ['edit_thread', 'new_thread']:
  41. del self.layout[0][1][0]
  42. else:
  43. self.fields['thread_name'] = forms.CharField(
  44. max_length=self.request.settings['thread_name_max'],
  45. validators=[validate_sluggable(
  46. _("Thread name must contain at least one alpha-numeric character."),
  47. _("Thread name is too long. Try shorter name.")
  48. )])
  49. def clean_post(self):
  50. data = self.cleaned_data['post']
  51. if len(data) < self.request.settings['post_length_min']:
  52. raise forms.ValidationError(ungettext(
  53. "Post content cannot be empty.",
  54. "Post content cannot be shorter than %(count)d characters.",
  55. self.request.settings['post_length_min']
  56. ) % {'count': self.request.settings['post_length_min']})
  57. return data
  58. class QuickReplyForm(Form):
  59. post = forms.CharField(widget=forms.Textarea)
  60. class MoveThreadsForm(Form):
  61. error_source = 'new_forum'
  62. def __init__(self, data=None, request=None, forum=None, *args, **kwargs):
  63. self.forum = forum
  64. super(MoveThreadsForm, self).__init__(data, request=request, *args, **kwargs)
  65. def finalize_form(self):
  66. self.fields['new_forum'] = TreeNodeChoiceField(queryset=Forum.tree.get(token='root').get_descendants().filter(pk__in=self.request.acl.forums.acl['can_browse']),level_indicator=u'- - ')
  67. self.layout = [
  68. [
  69. _("Thread Options"),
  70. [
  71. ('new_forum', {'label': _("Move Thread to"), 'help_text': _("Select forum you want to move threads to.")}),
  72. ],
  73. ],
  74. ]
  75. def clean_new_forum(self):
  76. new_forum = self.cleaned_data['new_forum']
  77. # Assert its forum and its not current forum
  78. if new_forum.type != 'forum':
  79. raise forms.ValidationError(_("This is not forum."))
  80. if new_forum.pk == self.forum.pk:
  81. raise forms.ValidationError(_("New forum is same as current one."))
  82. return new_forum
  83. class MergeThreadsForm(Form, ThreadNameMixin):
  84. def __init__(self, data=None, request=None, threads=[], *args, **kwargs):
  85. self.threads = threads
  86. super(MergeThreadsForm, self).__init__(data, request=request, *args, **kwargs)
  87. def finalize_form(self):
  88. self.fields['thread_name'] = forms.CharField(
  89. max_length=self.request.settings['thread_name_max'],
  90. initial=self.threads[0].name,
  91. validators=[validate_sluggable(
  92. _("Thread name must contain at least one alpha-numeric character."),
  93. _("Thread name is too long. Try shorter name.")
  94. )])
  95. self.layout = [
  96. [
  97. _("Thread Options"),
  98. [
  99. ('thread_name', {'label': _("Thread Name"), 'help_text': _("Name of new thread that will be created as result of merge.")}),
  100. ],
  101. ],
  102. [
  103. _("Merge Order"),
  104. [
  105. ],
  106. ],
  107. ]
  108. choices = []
  109. for i, thread in enumerate(self.threads):
  110. choices.append((str(i), i + 1))
  111. for i, thread in enumerate(self.threads):
  112. self.fields['thread_%s' % thread.pk] = forms.ChoiceField(choices=choices,initial=str(i))
  113. self.layout[1][1].append(('thread_%s' % thread.pk, {'label': thread.name}))
  114. def clean(self):
  115. cleaned_data = super(MergeThreadsForm, self).clean()
  116. self.merge_order = {}
  117. lookback = []
  118. for thread in self.threads:
  119. order = int(cleaned_data['thread_%s' % thread.pk])
  120. if order in lookback:
  121. raise forms.ValidationError(_("One or more threads have same position in merge order."))
  122. lookback.append(order)
  123. self.merge_order[order] = thread
  124. return cleaned_data