captcha.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. from django import forms
  2. from django.utils.translation import gettext_lazy as _
  3. from .base import ChangeSettingsForm
  4. class ChangeCaptchaSettingsForm(ChangeSettingsForm):
  5. settings = [
  6. "captcha_type",
  7. "recaptcha_site_key",
  8. "recaptcha_secret_key",
  9. "qa_question",
  10. "qa_help_text",
  11. "qa_answers",
  12. ]
  13. captcha_type = forms.ChoiceField(
  14. label=_("Enable CAPTCHA"),
  15. choices=[
  16. ("no", _("No CAPTCHA")),
  17. ("re", _("reCaptcha")),
  18. ("qa", _("Question and answer")),
  19. ],
  20. widget=forms.RadioSelect(),
  21. )
  22. recaptcha_site_key = forms.CharField(
  23. label=_("Site key"), max_length=100, required=False
  24. )
  25. recaptcha_secret_key = forms.CharField(
  26. label=_("Secret key"), max_length=100, required=False
  27. )
  28. qa_question = forms.CharField(
  29. label=_("Test question"), max_length=100, required=False
  30. )
  31. qa_help_text = forms.CharField(
  32. label=_("Question help text"), max_length=250, required=False
  33. )
  34. qa_answers = forms.CharField(
  35. label=_("Valid answers"),
  36. help_text=_("Enter each answer in new line. Answers are case-insensitive."),
  37. widget=forms.Textarea({"rows": 4}),
  38. max_length=250,
  39. required=False,
  40. )
  41. def clean(self):
  42. cleaned_data = super().clean()
  43. if cleaned_data.get("captcha_type") == "re":
  44. if not cleaned_data.get("recaptcha_site_key"):
  45. self.add_error(
  46. "recaptcha_site_key",
  47. _(
  48. "You need to enter site key if "
  49. "selected CAPTCHA type is reCaptcha."
  50. ),
  51. )
  52. if not cleaned_data.get("recaptcha_secret_key"):
  53. self.add_error(
  54. "recaptcha_secret_key",
  55. _(
  56. "You need to enter secret key if "
  57. "selected CAPTCHA type is reCaptcha."
  58. ),
  59. )
  60. if cleaned_data.get("captcha_type") == "qa":
  61. if not cleaned_data.get("qa_question"):
  62. self.add_error(
  63. "qa_question",
  64. _("You need to set question if selected CAPTCHA type is Q&A."),
  65. )
  66. if not cleaned_data.get("qa_answers"):
  67. self.add_error(
  68. "qa_answers",
  69. _(
  70. "You need to set question answers if "
  71. "selected CAPTCHA type is Q&A."
  72. ),
  73. )
  74. return cleaned_data