forms.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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.fields['thread_name']
  42. del self.layout[0][1][0]
  43. else:
  44. self.fields['thread_name'] = forms.CharField(
  45. max_length=self.request.settings['thread_name_max'],
  46. validators=[validate_sluggable(
  47. _("Thread name must contain at least one alpha-numeric character."),
  48. _("Thread name is too long. Try shorter name.")
  49. )])
  50. def clean_post(self):
  51. data = self.cleaned_data['post']
  52. if len(data) < self.request.settings['post_length_min']:
  53. raise forms.ValidationError(ungettext(
  54. "Post content cannot be empty.",
  55. "Post content cannot be shorter than %(count)d characters.",
  56. self.request.settings['post_length_min']
  57. ) % {'count': self.request.settings['post_length_min']})
  58. return data
  59. class QuickReplyForm(Form):
  60. post = forms.CharField(widget=forms.Textarea)
  61. class MoveThreadsForm(Form):
  62. error_source = 'new_forum'
  63. def __init__(self, data=None, request=None, forum=None, *args, **kwargs):
  64. self.forum = forum
  65. super(MoveThreadsForm, self).__init__(data, request=request, *args, **kwargs)
  66. def finalize_form(self):
  67. 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'- - ')
  68. self.layout = [
  69. [
  70. _("Thread Options"),
  71. [
  72. ('new_forum', {'label': _("Move Thread to"), 'help_text': _("Select forum you want to move threads to.")}),
  73. ],
  74. ],
  75. ]
  76. def clean_new_forum(self):
  77. new_forum = self.cleaned_data['new_forum']
  78. # Assert its forum and its not current forum
  79. if new_forum.type != 'forum':
  80. raise forms.ValidationError(_("This is not forum."))
  81. if new_forum.pk == self.forum.pk:
  82. raise forms.ValidationError(_("New forum is same as current one."))
  83. return new_forum
  84. class MergeThreadsForm(Form, ThreadNameMixin):
  85. def __init__(self, data=None, request=None, threads=[], *args, **kwargs):
  86. self.threads = threads
  87. super(MergeThreadsForm, self).__init__(data, request=request, *args, **kwargs)
  88. def finalize_form(self):
  89. self.fields['thread_name'] = forms.CharField(
  90. max_length=self.request.settings['thread_name_max'],
  91. initial=self.threads[0].name,
  92. validators=[validate_sluggable(
  93. _("Thread name must contain at least one alpha-numeric character."),
  94. _("Thread name is too long. Try shorter name.")
  95. )])
  96. self.layout = [
  97. [
  98. _("Thread Options"),
  99. [
  100. ('thread_name', {'label': _("Thread Name"), 'help_text': _("Name of new thread that will be created as result of merge.")}),
  101. ],
  102. ],
  103. [
  104. _("Merge Order"),
  105. [
  106. ],
  107. ],
  108. ]
  109. choices = []
  110. for i, thread in enumerate(self.threads):
  111. choices.append((str(i), i + 1))
  112. for i, thread in enumerate(self.threads):
  113. self.fields['thread_%s' % thread.pk] = forms.ChoiceField(choices=choices,initial=str(i))
  114. self.layout[1][1].append(('thread_%s' % thread.pk, {'label': thread.name}))
  115. def clean(self):
  116. cleaned_data = super(MergeThreadsForm, self).clean()
  117. self.merge_order = {}
  118. lookback = []
  119. for thread in self.threads:
  120. order = int(cleaned_data['thread_%s' % thread.pk])
  121. if order in lookback:
  122. raise forms.ValidationError(_("One or more threads have same position in merge order."))
  123. lookback.append(order)
  124. self.merge_order[order] = thread
  125. return cleaned_data