forms.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from django import forms
  2. from django.db.models import Q
  3. from django.utils.translation import gettext_lazy as _
  4. from .models import Agreement
  5. from .utils import set_agreement_as_active
  6. class AgreementForm(forms.ModelForm):
  7. type = forms.ChoiceField(label=_("Type"), choices=Agreement.TYPE_CHOICES)
  8. title = forms.CharField(
  9. label=_("Title"),
  10. help_text=_("Optional, leave empty for agreement to be named after its type."),
  11. required=False,
  12. )
  13. is_active = forms.BooleanField(
  14. label=_("Set as active for its type"),
  15. help_text=_(
  16. "If other agreement is already active for this type, it will be unset "
  17. "and replaced with this one. "
  18. "Misago will ask users who didn't accept this agreement to do so "
  19. "before allowing them to continue using the site's features."
  20. ),
  21. required=False,
  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. Agreement.objects.invalidate_cache()
  49. return agreement
  50. class FilterAgreementsForm(forms.Form):
  51. type = forms.MultipleChoiceField(
  52. label=_("Type"), required=False, choices=Agreement.TYPE_CHOICES
  53. )
  54. content = forms.CharField(label=_("Content"), required=False)
  55. def filter_queryset(self, criteria, queryset):
  56. if criteria.get("type") is not None:
  57. queryset = queryset.filter(type__in=criteria["type"])
  58. if criteria.get("content"):
  59. search_title = Q(title__icontains=criteria["content"])
  60. search_text = Q(text__icontains=criteria["content"])
  61. queryset = queryset.filter(search_title | search_text)
  62. return queryset