analytics.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import re
  2. from django import forms
  3. from django.utils.translation import gettext_lazy as _
  4. from .base import ChangeSettingsForm
  5. GOOGLE_SITE_VERIFICATION = re.compile(
  6. "^google-site-verification: google([0-9a-z]+)\.html$"
  7. )
  8. class ChangeAnalyticsSettingsForm(ChangeSettingsForm):
  9. settings = ["google_tracking_id", "google_site_verification"]
  10. google_tracking_id = forms.CharField(
  11. label=_("Tracking ID"),
  12. help_text=_(
  13. "Setting the Tracking ID will result in gtag.js file being included in "
  14. "your site's HTML markup, enabling Google Analytics integration."
  15. ),
  16. required=False,
  17. )
  18. google_site_verification = forms.CharField(
  19. label=_("Site verification token"),
  20. help_text=_(
  21. "This token was extracted from uploaded site verification file. "
  22. "To change it, upload new verification file."
  23. ),
  24. required=False,
  25. disabled=True,
  26. )
  27. google_site_verification_file = forms.FileField(
  28. label=_("Upload site verification file"),
  29. help_text=_(
  30. "Site verification file can be downloaded from Search Console's "
  31. '"Ownership verification" page.'
  32. ),
  33. required=False,
  34. )
  35. def clean_google_site_verification_file(self):
  36. upload = self.cleaned_data.get("google_site_verification_file")
  37. if not upload:
  38. return None
  39. if upload.content_type != "text/html":
  40. raise forms.ValidationError(_("Uploaded file type is not HTML."))
  41. file_content = upload.read().decode("utf-8")
  42. content_match = GOOGLE_SITE_VERIFICATION.match(file_content)
  43. if not content_match:
  44. raise forms.ValidationError(
  45. _("Uploaded file did not contain a verification code.")
  46. )
  47. return content_match.group(1)
  48. def clean(self):
  49. cleaned_data = super().clean()
  50. if cleaned_data.get("google_site_verification_file"):
  51. new_verification = cleaned_data.pop("google_site_verification_file")
  52. cleaned_data["google_site_verification"] = new_verification
  53. return cleaned_data