54
First, create a way to have your development and production servers pull settings from different files, say dev.py and prod.py. There are lots of ways to do this.
Then, create a setting, GOOGLE_ANALYTICS_KEY
. In dev.py set it to the empty string. In prod.py, set it to your key, something like “UA-124465-1”. Create a context processor to add this setting to all your template contexts, either as GOOGLE_ANALYTICS_KEY
, or just go ahead and add your settings module. Then, in your template, use it to conditionally include your analytics code:
{% if settings.GOOGLE_ANALYTICS_KEY %}
<script> blah blah {{settings.GOOGLE_ANALYTICS_KEY}} blah blah </script>
{% endif %}
15
A little late to the party, but there’s a reusable Django app called django-google-analytics. The easiest way to use it is:
- Add the
google_analytics
application to yourINSTALLED_APPS
section of yoursettings.py
. - In your base template, usually a
base.html
, insert this tag at the very top:{% load analytics %}
- In the same template, insert the following code right before the closing body tag:
{% analytics "UA-xxxxxx-x" %}
theUA-xxxxxx-x
is a unique Google Analytics code for your domain.
- [Django]-SocketException: OS Error: Connection refused, errno = 111 in flutter using django backend
- [Django]-Tying in to Django Admin's Model History
- [Django]-Why does Django Rest Framework discourage model level validation?
9
My solution takes a similar approach to Ned’s preferred answer, but separates the analytics code into its own template. I prefer this, so I can just copy the template from project to project.
Here’s a snippet from my context_processor file:
from django.conf import settings
from django.template.loader import render_to_string
def analytics(request):
"""
Returns analytics code.
"""
if not settings.DEBUG:
return { 'analytics_code': render_to_string("analytics/analytics.html", { 'google_analytics_key: settings.GOOGLE_ANALYTICS_KEY }) }
else:
return { 'analytics_code': "" }
Of course you’ll need to tell Django to include this in your context. In in your settings.py file, include:
TEMPLATE_CONTEXT_PROCESSORS = (
...
"context_processors.analytics",
)
I have it set up to include the analytics code only when DEBUG is set to False, but you may prefer to key it off something else, perhaps a new setting altogether. I think DEBUG is a good default since it supposes you don’t want to track any hits while debugging/developing.
Create a setting with your Google Analytics Key:
GOOGLE_ANALYTICS_KEY = "UA-1234567-8"
Create a template called: “analytics/analytics.html” that includes something like this:
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("{{ google_analytics_key }}");
pageTracker._trackPageview();
} catch(err) {}</script>
Finally, just before the closing tag in your base.html template, add this:
{{ analytics_code }}
Now your analytics code will be included only when DEBUG=False. Otherwise, nothing will be included.
- [Django]-Open the file in universal-newline mode using the CSV Django module
- [Django]-Need to convert a string to int in a django template
- [Django]-How do I do a not equal in Django queryset filtering?
5
All of these other solutions may work, but they are all overkill now because you can easily set up a filter in Google Analytics to filter out all traffic that is not coming from your production website or websites. See Create/Manage Profile Filters in the GA Help. A solution with no code just makes everybody’s life easier.
Note: there are two caveats
- this doesn’t work with realtime filtering, because no filters are applied to realtime (as of July 2012–check their documents)
- you have to be an admin with the Google Analytics account to set this up
- [Django]-Django, query filtering from model method
- [Django]-Is it possible to use FastAPI with Django?
- [Django]-Remove and ignore all files that have an extension from a git repository
4
Another simple way.
In settings.py
,Check debug
is True
, then add:
INTERNAL_IPS = (
'127.0.0.1',
'localhost',
)
Then you can use things in your template like this:
{% if not debug %}
<script> blah blah </script>
{% endif %}
If want to change to production, set debug
to False
.
- [Django]-Class views in Django
- [Django]-Django query filter with variable column
- [Django]-TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
2
I mostly agree with Ned, although I have a single setting called IS_LIVE_SITE which toggles analytics code, adverts and a few other things. This way I can keep all the keys in subversion (as it is a pain to look them up) and still toggle them on or off easily.
- [Django]-Request.user returns a SimpleLazyObject, how do I "wake" it?
- [Django]-AttributeError: 'module' object has no attribute 'tests'
- [Django]-Django-tables2: How to use accessor to bring in foreign columns?
2
Instead of including the script tag directly in your html, just change the analytics javascript so it only runs if the href does not contain your prod site’s name. This will work without any extra configuration.
- [Django]-Proper way to consume data from RESTFUL API in django
- [Django]-Unittest Django: Mock external API, what is proper way?
- [Django]-Why would running scheduled tasks with Celery be preferable over crontab?
1
You have template context processors that can be used to pass values to all templates without updating all your views.
http://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
- [Django]-Django is "unable to open database file"
- [Django]-Missing Table When Running Django Unittest with Sqlite3
- [Django]-Django – set user permissions when user is automatically created using get_or_create
1
Hi all it’s a quite old post..
But since I spent some time in searching some reusable app that is still actively maintained I want to share what I found:
https://github.com/jcassee/django-analytical
This project is still actively maintained and does not require the ID to be added to the database (I think is better if you have one project per site) so it is bared in the code no matter if the environment is development or production.
- [Django]-Installing python dateutil
- [Django]-How to render an ordered dictionary in django templates?
- [Django]-How to upload multiple images to a blog post in django
0
Here’s the dead simple way that I solved it:
Create an app in your project called ‘utils’ if you haven’t already. See these directions.
However, follow this approach to include all global context processers in addition to the project settings. It’s seems to be a better practice. Here are the instructions.
So, after you create your ‘utils’ app, create a a file called context_processors.py in /utils that looks like this:
from django.conf import settings
def googleanalytics(request):
return {
'google_tracking_id' : settings.GOOGLE_TRACKING_ID,
}
In you settings.py file, add this:
import django.conf.global_settings as DEFAULT_SETTINGS
TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
'utils.context_processors.googleanalytics',
)
Hope this helps!
- [Django]-How can i test for an empty queryset in Django?
- [Django]-Mac OS X – EnvironmentError: mysql_config not found
- [Django]-Django template tag to truncate text