forms.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. from django import forms
  2. from django.db.models import Q
  3. from django.utils.translation import gettext_lazy as _
  4. from ...admin.forms import YesNoSwitch
  5. from ..models import Agreement
  6. from .utils import disable_agreement, set_agreement_as_active
  7. class AgreementForm(forms.ModelForm):
  8. type = forms.ChoiceField(label=_("Type"), choices=Agreement.TYPE_CHOICES)
  9. title = forms.CharField(
  10. label=_("Title"),
  11. help_text=_("Optional, leave empty for agreement to be named after its type."),
  12. required=False,
  13. )
  14. is_active = YesNoSwitch(
  15. label=_("Active for its type"),
  16. help_text=_(
  17. "If other agreement is already active for this type, it will be unset "
  18. "and replaced with this one. "
  19. "Misago will ask users who didn't accept this agreement to do so "
  20. "before allowing them to continue using the site."
  21. ),
  22. )
  23. link = forms.URLField(
  24. label=_("Link"),
  25. help_text=_(
  26. "If your agreement is located on other page, enter here a link to it."
  27. ),
  28. required=False,
  29. )
  30. text = forms.CharField(
  31. label=_("Text"),
  32. help_text=_("You can use Markdown syntax for rich text elements."),
  33. widget=forms.Textarea,
  34. required=False,
  35. )
  36. class Meta:
  37. model = Agreement
  38. fields = ["type", "title", "link", "text", "is_active"]
  39. def clean(self):
  40. data = super().clean()
  41. if not data.get("link") and not data.get("text"):
  42. raise forms.ValidationError(_("Please fill in agreement link or text."))
  43. return data
  44. def save(self):
  45. agreement = super().save()
  46. if agreement.is_active:
  47. set_agreement_as_active(agreement)
  48. else:
  49. disable_agreement(agreement)
  50. Agreement.objects.invalidate_cache()
  51. return agreement
  52. class FilterAgreementsForm(forms.Form):
  53. type = forms.ChoiceField(
  54. label=_("Type"),
  55. required=False,
  56. choices=[("", _("All types"))] + Agreement.TYPE_CHOICES,
  57. )
  58. content = forms.CharField(label=_("Content"), required=False)
  59. def filter_queryset(self, criteria, queryset):
  60. if criteria.get("type") is not None:
  61. queryset = queryset.filter(type=criteria["type"])
  62. if criteria.get("content"):
  63. search_title = Q(title__icontains=criteria["content"])
  64. search_text = Q(text__icontains=criteria["content"])
  65. queryset = queryset.filter(search_title | search_text)
  66. return queryset