Deploying Google Analytics With Django

后端 未结 10 1138
遇见更好的自我
遇见更好的自我 2020-12-23 11:29

We\'re about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don\'t want all of the hits on developmen

相关标签:
10条回答
  • 2020-12-23 12:22

    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 %}
    
    0 讨论(0)
  • 2020-12-23 12:23

    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.

    0 讨论(0)
  • 2020-12-23 12:26

    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

    1. this doesn't work with realtime filtering, because no filters are applied to realtime (as of July 2012--check their documents)
    2. you have to be an admin with the Google Analytics account to set this up
    0 讨论(0)
  • 2020-12-23 12:31

    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

    0 讨论(0)
提交回复
热议问题