I'm running into an issue and would appreciate some pointers. I have a production Django app where I included Google Analytics using a context processor and conditionally render it in my base.html template like this:
<!-- Google Analytics -->
{% if GOOGLE_ANALYTICS_ID %}
<script async src="https://www.googletagmanager.com/gtag/js?id={{ GOOGLE_ANALYTICS_ID }}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', '{{ GOOGLE_ANALYTICS_ID }}');
</script>
{% endif %}
<!-- End Google Analytics -->
Everything was working fine but the GA tracking completely breaks after enabling django_minify_html
These are my current settings:
For base.py:
USE_MINIFICATION = DJANGO_ENV == "production"
MINIFY_HTML = {
"enabled": USE_MINIFICATION,
"remove_comments": True,
"minify_js": False,
"minify_css": True,
}
For production.py
from .base import MIDDLEWARE as BASE_MIDDLEWARE
MIDDLEWARE = list(BASE_MIDDLEWARE)
# Insert MinifyHtmlMiddleware after WhiteNoiseMiddleware
try:
whitenoise_index = MIDDLEWARE.index("whitenoise.middleware.WhiteNoiseMiddleware")
MIDDLEWARE.insert(whitenoise_index + 1, "django_minify_html.middleware.MinifyHtmlMiddleware")
except ValueError:
try:
security_index = MIDDLEWARE.index("django.middleware.security.SecurityMiddleware")
MIDDLEWARE.insert(security_index + 1, "django_minify_html.middleware.MinifyHtmlMiddleware")
except ValueError:
MIDDLEWARE.insert(0, "django_minify_html.middleware.MinifyHtmlMiddleware")
Has anyone encountered this before? I've minify_js to False in hopes to exclude the GA script but keep on getting the console error.
Would love to hear any tips or workarounds for the best way to exclude GA tracking code from compression/minification.
Thanks!
MINIFY_HTML?django-minify-htmldoesn't have any configurable settings. Also what do you see in place of the GA code when you click View Source in the web browser?js,new Date());gtag(config,G-MYVALUE_ASPER.ENV)</script>"settings.py(unless you make your own subclass and use it as the middleware as documented). Regarding the script tag: The error handler might have re-formatted the script tag. To make sure, use the View Source function of your browser and copy the GA script from the HTML. Don't post it as a comment as it becomes unreadable. Edit your question and add the extra information there, properly formatted.