forms.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 * # noqa
  5. from misago.core import forms
  6. from misago.core.validators import validate_sluggable
  7. from misago.forums.models import FORUMS_TREE_ID, Forum, ForumRole
  8. """
  9. Fields
  10. """
  11. class AdminForumFieldMixin(object):
  12. def __init__(self, *args, **kwargs):
  13. self.base_level = kwargs.pop('base_level', 1)
  14. kwargs['level_indicator'] = kwargs.get('level_indicator', '- - ')
  15. kwargs.setdefault('queryset',
  16. Forum.objects.filter(tree_id=FORUMS_TREE_ID))
  17. super(AdminForumFieldMixin, self).__init__(*args, **kwargs)
  18. def _get_level_indicator(self, obj):
  19. level = getattr(obj, obj._mptt_meta.level_attr) - self.base_level
  20. if level > 0:
  21. return mark_safe(conditional_escape(self.level_indicator) * level)
  22. else:
  23. return ''
  24. class AdminForumChoiceField(AdminForumFieldMixin, TreeNodeChoiceField):
  25. pass
  26. class AdminForumMultipleChoiceField(AdminForumFieldMixin,
  27. TreeNodeMultipleChoiceField):
  28. pass
  29. class MisagoForumMixin(object):
  30. def __init__(self, *args, **kwargs):
  31. self.parent = None
  32. if not 'queryset' in kwargs:
  33. kwargs['queryset'] = Forum.objects.order_by('lft')
  34. super(MisagoForumMixin, self).__init__(*args, **kwargs)
  35. def set_acl(self, acl=None):
  36. queryset = Forum.objects.root_category().get_descendants()
  37. if acl:
  38. allowed_ids = [0]
  39. for forum_id, perms in acl.get('forums', {}).items():
  40. if perms.get('can_see') and perms.get('can_browse'):
  41. allowed_ids.append(forum_id)
  42. queryset = queryset.filter(id__in=allowed_ids)
  43. self.queryset = queryset
  44. def _get_level_indicator(self, obj):
  45. level = obj.level - 1
  46. return mark_safe(conditional_escape('- - ') * level)
  47. class ForumChoiceField(MisagoForumMixin, TreeNodeChoiceField):
  48. pass
  49. class ForumsMultipleChoiceField(MisagoForumMixin, TreeNodeMultipleChoiceField):
  50. pass
  51. """
  52. Forms
  53. """
  54. FORUM_ROLES = (
  55. ('category', _('Category')),
  56. ('forum', _('Forum')),
  57. ('redirect', _('Redirect')),
  58. )
  59. class ForumFormBase(forms.ModelForm):
  60. role = forms.ChoiceField(label=_("Type"), choices=FORUM_ROLES)
  61. name = forms.CharField(
  62. label=_("Name"),
  63. validators=[validate_sluggable()])
  64. description = forms.CharField(
  65. label=_("Description"), max_length=2048, required=False,
  66. widget=forms.Textarea(attrs={'rows': 3}),
  67. help_text=_("Optional description explaining forum intented "
  68. "purpose."))
  69. redirect_url = forms.URLField(
  70. label=_("Redirect URL"),
  71. validators=[validate_sluggable()],
  72. help_text=_('If forum type is redirect, enter here its URL.'),
  73. required=False)
  74. css_class = forms.CharField(
  75. label=_("CSS class"), required=False,
  76. help_text=_("Optional CSS class used to customize this forum "
  77. "appearance from templates."))
  78. is_closed = forms.YesNoSwitch(
  79. label=_("Closed forum"), required=False,
  80. help_text=_("Only members with valid permissions can post in "
  81. "closed forums."))
  82. css_class = forms.CharField(
  83. label=_("CSS class"), required=False,
  84. help_text=_("Optional CSS class used to customize this forum "
  85. "appearance from templates."))
  86. prune_started_after = forms.IntegerField(
  87. label=_("Thread age"), min_value=0,
  88. help_text=_("Prune thread if number of days since its creation is "
  89. "greater than specified. Enter 0 to disable this "
  90. "pruning criteria."))
  91. prune_replied_after = forms.IntegerField(
  92. label=_("Last reply"), min_value=0,
  93. help_text=_("Prune thread if number of days since last reply is "
  94. "greater than specified. Enter 0 to disable this "
  95. "pruning criteria."))
  96. class Meta:
  97. model = Forum
  98. fields = [
  99. 'role',
  100. 'name',
  101. 'description',
  102. 'redirect_url',
  103. 'css_class',
  104. 'is_closed',
  105. 'prune_started_after',
  106. 'prune_replied_after',
  107. 'archive_pruned_in',
  108. ]
  109. def clean_copy_permissions(self):
  110. data = self.cleaned_data['copy_permissions']
  111. if data and data.pk == self.instance.pk:
  112. message = _("Permissions cannot be copied from forum into itself.")
  113. raise forms.ValidationError(message)
  114. return data
  115. def clean_archive_pruned_in(self):
  116. data = self.cleaned_data['archive_pruned_in']
  117. if data and data.pk == self.instance.pk:
  118. message = _("Forum cannot act as archive for itself.")
  119. raise forms.ValidationError(message)
  120. return data
  121. def clean(self):
  122. data = super(ForumFormBase, self).clean()
  123. self.instance.set_name(data.get('name'))
  124. if data['role'] != 'category':
  125. if not data['new_parent'].level:
  126. message = _("Only categories can have no parent category.")
  127. raise forms.ValidationError(message)
  128. if data['role'] == 'redirect':
  129. if not data.get('redirect_url'):
  130. message = _("This forum is redirect, yet you haven't "
  131. "specified URL to which it should redirect "
  132. "after click.")
  133. raise forms.ValidationError(message)
  134. return data
  135. def ForumFormFactory(instance):
  136. parent_queryset = Forum.objects.all_forums(True).order_by('lft')
  137. if instance.pk:
  138. not_siblings = models.Q(lft__lt=instance.lft)
  139. not_siblings = not_siblings | models.Q(rght__gt=instance.rght)
  140. parent_queryset = parent_queryset.filter(not_siblings)
  141. return type('ForumFormFinal', (ForumFormBase,), {
  142. 'new_parent': AdminForumChoiceField(
  143. label=_("Parent forum"),
  144. queryset=parent_queryset,
  145. initial=instance.parent,
  146. empty_label=None),
  147. 'copy_permissions': AdminForumChoiceField(
  148. label=_("Copy permissions"),
  149. help_text=_("You can replace this forum permissions with "
  150. "permissions copied from forum selected here."),
  151. queryset=Forum.objects.all_forums(),
  152. empty_label=_("Don't copy permissions"),
  153. required=False),
  154. 'archive_pruned_in': AdminForumChoiceField(
  155. label=_("Archive"),
  156. help_text=_("Instead of being deleted, pruned threads can be "
  157. "moved to designated forum."),
  158. queryset=Forum.objects.all_forums(),
  159. empty_label=_("Don't archive pruned threads"),
  160. required=False),
  161. })
  162. class DeleteForumFormBase(forms.ModelForm):
  163. class Meta:
  164. model = Forum
  165. fields = []
  166. def clean(self):
  167. data = super(DeleteForumFormBase, self).clean()
  168. if data.get('move_threads_to'):
  169. if data['move_threads_to'].pk == self.instance.pk:
  170. message = _("You are trying to move this forum threads to "
  171. "itself.")
  172. raise forms.ValidationError(message)
  173. if data['move_threads_to'].role == 'category':
  174. message = _("Threads can't be moved to category.")
  175. raise forms.ValidationError(message)
  176. if data['move_threads_to'].role == 'redirect':
  177. message = _("Threads can't be moved to redirect.")
  178. raise forms.ValidationError(message)
  179. moving_to_child = self.instance.has_child(data['move_threads_to'])
  180. if moving_to_child and not data.get('move_children_to'):
  181. message = _("You are trying to move this forum threads to a "
  182. "child forum that will be deleted together with "
  183. "this forum.")
  184. raise forms.ValidationError(message)
  185. if data.get('move_children_to'):
  186. if data['move_children_to'].special_role == 'root_category':
  187. for child in self.instance.get_children().iterator():
  188. if child.role != 'category':
  189. message = _("One or more child forums in forum are "
  190. "not categories and thus cannot be made "
  191. "root categories.")
  192. raise forms.ValidationError(message)
  193. return data
  194. def DeleteFormFactory(instance):
  195. content_queryset = Forum.objects.all_forums().order_by('lft')
  196. fields = {
  197. 'move_threads_to': AdminForumChoiceField(
  198. label=_("Move forum threads to"),
  199. queryset=content_queryset,
  200. initial=instance.parent,
  201. empty_label=_('Delete with forum'),
  202. required=False),
  203. }
  204. not_siblings = models.Q(lft__lt=instance.lft)
  205. not_siblings = not_siblings | models.Q(rght__gt=instance.rght)
  206. children_queryset = Forum.objects.all_forums(True)
  207. children_queryset = children_queryset.filter(not_siblings).order_by('lft')
  208. if children_queryset.exists():
  209. fields['move_children_to'] = AdminForumChoiceField(
  210. label=_("Move child forums to"),
  211. queryset=children_queryset,
  212. empty_label=_('Delete with forum'),
  213. required=False)
  214. return type('DeleteForumFormFinal', (DeleteForumFormBase,), fields)
  215. class ForumRoleForm(forms.ModelForm):
  216. name = forms.CharField(label=_("Role name"))
  217. class Meta:
  218. model = ForumRole
  219. fields = ['name']
  220. def RoleForumACLFormFactory(forum, forum_roles, selected_role):
  221. attrs = {
  222. 'forum': forum,
  223. 'role': forms.ModelChoiceField(
  224. label=_("Role"),
  225. required=False,
  226. queryset=forum_roles,
  227. initial=selected_role,
  228. empty_label=_("No access"))
  229. }
  230. return type('RoleForumACLForm', (forms.Form,), attrs)
  231. def ForumRolesACLFormFactory(role, forum_roles, selected_role):
  232. attrs = {
  233. 'role': role,
  234. 'forum_role': forms.ModelChoiceField(
  235. label=_("Role"),
  236. required=False,
  237. queryset=forum_roles,
  238. initial=selected_role,
  239. empty_label=_("No access"))
  240. }
  241. return type('ForumRolesACLForm', (forms.Form,), attrs)