Deploying Google Analytics With Django

后端 未结 10 1159
遇见更好的自我
遇见更好的自我 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:16

    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:

    
    
    

    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.

提交回复
热议问题