forms.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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, ForumRole
  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. description = forms.CharField(
  30. label=_("Description"), max_length=2048, required=False,
  31. widget=forms.Textarea(attrs={'rows': 3}),
  32. help_text=_("Optional description explaining forum intented "
  33. "purpose."))
  34. redirect_url = forms.URLField(
  35. label=_("Redirect URL"),
  36. validators=[validate_sluggable()],
  37. help_text=_('If forum type is redirect, enter here its URL.'),
  38. required=False)
  39. css_class = forms.CharField(
  40. label=_("CSS class"), required=False,
  41. help_text=_("Optional CSS class used to customize this forum "
  42. "appearance from templates."))
  43. is_closed = forms.YesNoSwitch(
  44. label=_("Closed forum"), required=False,
  45. help_text=_("Only members with valid permissions can post in "
  46. "closed forums."))
  47. css_class = forms.CharField(
  48. label=_("CSS class"), required=False,
  49. help_text=_("Optional CSS class used to customize this forum "
  50. "appearance from templates."))
  51. prune_started_after = forms.IntegerField(
  52. label=_("Prune thread if number of days since its creation is "
  53. "greater than"), min_value=0,
  54. help_text=_("Enter 0 to disable this pruning criteria."))
  55. prune_replied_after = forms.IntegerField(
  56. label=_("Prune thread if number of days since last reply is greater "
  57. "than"), min_value=0,
  58. help_text=_("Enter 0 to disable this pruning criteria."))
  59. class Meta:
  60. model = Forum
  61. fields = [
  62. 'role',
  63. 'name',
  64. 'description',
  65. 'redirect_url',
  66. 'css_class',
  67. 'is_closed',
  68. 'prune_started_after',
  69. 'prune_replied_after',
  70. 'archive_pruned_in',
  71. ]
  72. def clean_copy_permissions(self):
  73. data = self.cleaned_data['copy_permissions']
  74. if data and data.pk == self.instance.pk:
  75. message = _("Permissions cannot be copied from forum into itself.")
  76. raise forms.ValidationError(message)
  77. return data
  78. def clean_archive_pruned_in(self):
  79. data = self.cleaned_data['archive_pruned_in']
  80. if data and data.pk == self.instance.pk:
  81. message = _("Forum cannot act as archive for itself.")
  82. raise forms.ValidationError(message)
  83. return data
  84. def clean(self):
  85. data = super(ForumFormBase, self).clean()
  86. self.instance.set_name(data.get('name'))
  87. self.instance.set_description(data.get('description'))
  88. if data['role'] != 'category':
  89. if not data['new_parent'].level:
  90. message = _("Only categories can have no parent category.")
  91. raise forms.ValidationError(message)
  92. if data['role'] == 'redirect':
  93. if not data.get('redirect'):
  94. message = _("This forum is redirect, yet you haven't "
  95. "specified URL to which it should redirect "
  96. "after click.")
  97. raise forms.ValidationError(message)
  98. return data
  99. def ForumFormFactory(instance):
  100. parent_queryset = Forum.objects.all_forums(True).order_by('lft')
  101. if instance.pk:
  102. not_siblings = models.Q(lft__lt=instance.lft)
  103. not_siblings = not_siblings | models.Q(rght__gt=instance.rght)
  104. parent_queryset = parent_queryset.filter(not_siblings)
  105. return type('ForumFormFinal', (ForumFormBase,), {
  106. 'new_parent': ForumChoiceField(
  107. label=_("Parent forum"),
  108. queryset=parent_queryset,
  109. initial=instance.parent,
  110. empty_label=None),
  111. 'copy_permissions': ForumChoiceField(
  112. label=_("Copy permissions"),
  113. help_text=_("You can override this forum permissions with "
  114. "permissions of other forum selected here."),
  115. queryset=Forum.objects.all_forums(),
  116. empty_label=_("Don't copy permissions"),
  117. base_level=1,
  118. required=False),
  119. 'archive_pruned_in': ForumChoiceField(
  120. label=_("Pruned threads archive"),
  121. help_text=_("Instead of being deleted, pruned threads can be "
  122. "moved to designated forum."),
  123. queryset=Forum.objects.all_forums(),
  124. empty_label=_("Don't archive pruned threads"),
  125. base_level=1,
  126. required=False),
  127. })
  128. class DeleteForumFormBase(forms.ModelForm):
  129. class Meta:
  130. model = Forum
  131. fields = []
  132. def clean(self):
  133. data = super(DeleteForumFormBase, self).clean()
  134. if data.get('move_threads_to'):
  135. if data['move_threads_to'].pk == self.instance.pk:
  136. message = _("You are trying to move this forum threads to "
  137. "itself.")
  138. raise forms.ValidationError(message)
  139. if data['move_threads_to'].role == 'category':
  140. message = _("Threads can't be moved to category.")
  141. raise forms.ValidationError(message)
  142. if data['move_threads_to'].role == 'redirect':
  143. message = _("Threads can't be moved to redirect.")
  144. raise forms.ValidationError(message)
  145. moving_to_child = self.instance.has_child(data['move_threads_to'])
  146. if moving_to_child and not data.get('move_children_to'):
  147. message = _("You are trying to move this forum threads to a "
  148. "child forum that will be deleted together with "
  149. "this forum.")
  150. raise forms.ValidationError(message)
  151. if data.get('move_children_to'):
  152. if data['move_children_to'].special_role == 'root_category':
  153. for child in self.instance.get_children().iterator():
  154. if child.role != 'category':
  155. message = _("One or more child forums in forum are not "
  156. "categories and thus cannot be made root "
  157. "categories.")
  158. raise forms.ValidationError(message)
  159. return data
  160. def DeleteFormFactory(instance):
  161. content_queryset = Forum.objects.all_forums().order_by('lft')
  162. fields = {
  163. 'move_threads_to': ForumChoiceField(
  164. label=_("Move forum threads to"),
  165. queryset=content_queryset,
  166. initial=instance.parent,
  167. empty_label=_('Delete with forum'),
  168. required=False),
  169. }
  170. not_siblings = models.Q(lft__lt=instance.lft)
  171. not_siblings = not_siblings | models.Q(rght__gt=instance.rght)
  172. children_queryset = Forum.objects.all_forums(True)
  173. children_queryset = children_queryset.filter(not_siblings).order_by('lft')
  174. if children_queryset.exists():
  175. fields['move_children_to'] = ForumChoiceField(
  176. label=_("Move child forums to"),
  177. queryset=children_queryset,
  178. empty_label=_('Delete with forum'),
  179. required=False)
  180. return type('DeleteForumFormFinal', (DeleteForumFormBase,), fields)
  181. class ForumRoleForm(forms.ModelForm):
  182. name = forms.CharField(label=_("Role name"))
  183. class Meta:
  184. model = ForumRole
  185. fields = ['name']
  186. def RoleForumACLFormFactory(forum, forum_roles, selected_role):
  187. attrs = {
  188. 'forum': forum,
  189. 'role': forms.ModelChoiceField(
  190. label=_("Role"),
  191. required=False,
  192. queryset=forum_roles,
  193. initial=selected_role,
  194. empty_label=_("No access"))
  195. }
  196. return type('RoleForumACLForm', (forms.Form,), attrs)
  197. def ForumRolesACLFormFactory(role, forum_roles, selected_role):
  198. attrs = {
  199. 'role': role,
  200. 'forum_role': forms.ModelChoiceField(
  201. label=_("Role"),
  202. required=False,
  203. queryset=forum_roles,
  204. initial=selected_role,
  205. empty_label=_("No access"))
  206. }
  207. return type('ForumRolesACLForm', (forms.Form,), attrs)