forms.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. from django.db import models
  2. from django.utils.html import conditional_escape, mark_safe
  3. from django.utils.translation import ugettext_lazy as _
  4. from mptt.forms import TreeNodeChoiceField as TreeNodeChoiceField
  5. from misago.core import forms
  6. from misago.core.validators import validate_sluggable
  7. from misago.forums.models import Forum
  8. class ForumChoiceField(TreeNodeChoiceField):
  9. def __init__(self, *args, **kwargs):
  10. self.base_level = kwargs.pop('base_level', 1)
  11. kwargs['level_indicator'] = kwargs.get('level_indicator', '- - ')
  12. super(ForumChoiceField, self).__init__(*args, **kwargs)
  13. def _get_level_indicator(self, obj):
  14. level = getattr(obj, obj._mptt_meta.level_attr) - self.base_level
  15. if level > 0:
  16. return mark_safe(conditional_escape(self.level_indicator) * level)
  17. else:
  18. return ''
  19. FORUM_ROLES = (
  20. ('category', _('Category')),
  21. ('forum', _('Forum')),
  22. ('redirect', _('Redirect')),
  23. )
  24. class ForumFormBase(forms.ModelForm):
  25. role = forms.ChoiceField(label=_("Type"), choices=FORUM_ROLES)
  26. name = forms.CharField(
  27. label=_("Name"),
  28. validators=[validate_sluggable()],
  29. help_text=_('Short and descriptive name of all users with this rank. '
  30. '"The Team" or "Game Masters" are good examples.'))
  31. description = forms.CharField(
  32. label=_("Description"), max_length=2048, required=False,
  33. widget=forms.Textarea(attrs={'rows': 3}),
  34. help_text=_("Optional description explaining forum's intented "
  35. "purpose."))
  36. redirect_url = forms.URLField(
  37. label=_("Redirect URL"),
  38. validators=[validate_sluggable()],
  39. help_text=_('If forum type is redirect, enter here its URL.'),
  40. required=False)
  41. css_class = forms.CharField(
  42. label=_("CSS class"), required=False,
  43. help_text=_("Optional CSS class used to customize this forum "
  44. "appearance from templates."))
  45. is_closed = forms.YesNoSwitch(
  46. label=_("Closed forum"), required=False,
  47. help_text=_("Only members with valid permissions can post in "
  48. "closed forums."))
  49. css_class = forms.CharField(
  50. label=_("CSS class"), required=False,
  51. help_text=_("Optional CSS class used to customize this forum "
  52. "appearance from templates."))
  53. prune_started_after = forms.IntegerField(
  54. label=_("Prune thread if number of days since its creation is "
  55. "greater than"), min_value=0,
  56. help_text=_("Enter 0 to disable this pruning criteria."))
  57. prune_replied_after = forms.IntegerField(
  58. label=_("Prune thread if number of days since last reply is greater "
  59. "than"), min_value=0,
  60. help_text=_("Enter 0 to disable this pruning criteria."))
  61. class Meta:
  62. model = Forum
  63. fields = [
  64. 'role',
  65. 'name',
  66. 'description',
  67. 'redirect_url',
  68. 'css_class',
  69. 'is_closed',
  70. 'prune_started_after',
  71. 'prune_replied_after',
  72. 'archive_pruned_in',
  73. ]
  74. def clean_copy_permissions(self):
  75. data = self.cleaned_data['copy_permissions']
  76. if data and data.pk == self.instance.pk:
  77. message = _("Permissions cannot be copied from forum into itself.")
  78. raise forms.ValidationError(message)
  79. return data
  80. def clean_archive_pruned_in(self):
  81. data = self.cleaned_data['archive_pruned_in']
  82. if data and data.pk == self.instance.pk:
  83. message = _("Forum cannot act as archive for itself.")
  84. raise forms.ValidationError(message)
  85. return data
  86. def clean(self):
  87. data = super(ForumFormBase, self).clean()
  88. self.instance.set_name(data.get('name'))
  89. self.instance.set_description(data.get('description'))
  90. if data['role'] != 'category':
  91. if not data['new_parent'].level:
  92. message = _("Only categories can have no parent category.")
  93. raise forms.ValidationError(message)
  94. if data['role'] == 'redirect':
  95. if not data.get('redirect'):
  96. message = _("This forum is redirect, yet you haven't "
  97. "specified URL to which it should redirect "
  98. "after click.")
  99. raise forms.ValidationError(message)
  100. return data
  101. def ForumFormFactory(instance):
  102. parent_queryset = Forum.objects.all_forums(True).order_by('lft')
  103. if instance.pk:
  104. not_siblings = models.Q(lft__lt=instance.lft)
  105. not_siblings = not_siblings | models.Q(rght__gt=instance.rght)
  106. parent_queryset = parent_queryset.filter(not_siblings)
  107. return type('ForumFormFinal', (ForumFormBase,), {
  108. 'new_parent': ForumChoiceField(
  109. label=_("Parent forum"),
  110. queryset=parent_queryset,
  111. initial=instance.parent,
  112. empty_label=None),
  113. 'copy_permissions': ForumChoiceField(
  114. label=_("Copy permissions"),
  115. help_text=_("You can override this forum permissions with "
  116. "permissions of other forum selected here."),
  117. queryset=Forum.objects.all_forums(),
  118. empty_label=_("Don't copy permissions"),
  119. base_level=1,
  120. required=False),
  121. 'archive_pruned_in': ForumChoiceField(
  122. label=_("Pruned threads archive"),
  123. help_text=_("Instead of being deleted, pruned threads can be "
  124. "moved to designated forum."),
  125. queryset=Forum.objects.all_forums(),
  126. empty_label=_("Don't archive pruned threads"),
  127. base_level=1,
  128. required=False),
  129. })
  130. class DeleteForumFormBase(forms.ModelForm):
  131. class Meta:
  132. model = Forum
  133. fields = []
  134. def clean(self):
  135. data = super(DeleteForumFormBase, self).clean()
  136. if data.get('move_threads_to'):
  137. if data['move_threads_to'].pk == self.instance.pk:
  138. message = _("You are trying to move this forum threads to "
  139. "itself.")
  140. raise forms.ValidationError(message)
  141. if data['move_threads_to'].role == 'category':
  142. message = _("Threads can't be moved to category.")
  143. raise forms.ValidationError(message)
  144. if data['move_threads_to'].role == 'redirect':
  145. message = _("Threads can't be moved to redirect.")
  146. raise forms.ValidationError(message)
  147. moving_to_child = self.instance.has_child(data['move_threads_to'])
  148. if moving_to_child and not data.get('move_children_to'):
  149. message = _("You are trying to move this forum threads to a "
  150. "child forum that will be deleted together with "
  151. "this forum.")
  152. raise forms.ValidationError(message)
  153. if data.get('move_children_to'):
  154. if data['move_children_to'].special_role == 'root_category':
  155. for child in self.get_children().iterator():
  156. if child.role != 'category':
  157. message = _("One or more child forums in forum are not "
  158. "categories and thus cannot be made root "
  159. "categories.")
  160. raise forms.ValidationError(message)
  161. return data
  162. def DeleteFormFactory(instance):
  163. content_queryset = Forum.objects.all_forums().order_by('lft')
  164. fields = {
  165. 'move_threads_to': ForumChoiceField(
  166. label=_("Move forum threads to"),
  167. queryset=content_queryset,
  168. initial=instance.parent,
  169. empty_label=_('Delete with forum'),
  170. required=False),
  171. }
  172. not_siblings = models.Q(lft__lt=instance.lft)
  173. not_siblings = not_siblings | models.Q(rght__gt=instance.rght)
  174. children_queryset = Forum.objects.all_forums(True)
  175. children_queryset = children_queryset.filter(not_siblings).order_by('lft')
  176. if children_queryset.exists():
  177. fields['move_children_to'] = ForumChoiceField(
  178. label=_("Move child forums to"),
  179. queryset=children_queryset,
  180. empty_label=_('Delete with forum'),
  181. required=False)
  182. return type('DeleteForumFormFilan', (DeleteForumFormBase,), fields)