forms.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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=_("Thread age"), min_value=0,
  53. help_text=_("Prune thread if number of days since its creation is "
  54. "greater than specified. Enter 0 to disable this "
  55. "pruning criteria."))
  56. prune_replied_after = forms.IntegerField(
  57. label=_("Last reply"), min_value=0,
  58. help_text=_("Prune thread if number of days since last reply is "
  59. "greater than specified. Enter 0 to disable this "
  60. "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_url'):
  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 replace this forum permissions with "
  116. "permissions copied from 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=_("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.instance.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('DeleteForumFormFinal', (DeleteForumFormBase,), fields)
  183. class ForumRoleForm(forms.ModelForm):
  184. name = forms.CharField(label=_("Role name"))
  185. class Meta:
  186. model = ForumRole
  187. fields = ['name']
  188. def RoleForumACLFormFactory(forum, forum_roles, selected_role):
  189. attrs = {
  190. 'forum': forum,
  191. 'role': forms.ModelChoiceField(
  192. label=_("Role"),
  193. required=False,
  194. queryset=forum_roles,
  195. initial=selected_role,
  196. empty_label=_("No access"))
  197. }
  198. return type('RoleForumACLForm', (forms.Form,), attrs)
  199. def ForumRolesACLFormFactory(role, forum_roles, selected_role):
  200. attrs = {
  201. 'role': role,
  202. 'forum_role': forms.ModelChoiceField(
  203. label=_("Role"),
  204. required=False,
  205. queryset=forum_roles,
  206. initial=selected_role,
  207. empty_label=_("No access"))
  208. }
  209. return type('ForumRolesACLForm', (forms.Form,), attrs)