diff mbox

[Branch,~linaro-validation/lava-server/trunk] Rev 413: Add google analytics integration. Reviewed by terceiro.

Message ID 20130725120823.10631.92354.launchpad@ackee.canonical.com
State Accepted
Headers show

Commit Message

Stevan Radakovic July 25, 2013, 12:08 p.m. UTC
Merge authors:
  Stevan Radaković (stevanr)
Related merge proposals:
  https://code.launchpad.net/~stevanr/lava-server/add-google-analytics/+merge/176411
  proposed by: Stevan Radaković (stevanr)
  review: Approve - Antonio Terceiro (terceiro)
------------------------------------------------------------
revno: 413 [merge]
committer: Stevan Radakovic <stevan.radakovic@linaro.org>
branch nick: trunk
timestamp: Thu 2013-07-25 14:07:17 +0200
message:
  Add google analytics integration. Reviewed by terceiro.
added:
  google_analytics/
  google_analytics/LICENSE
  google_analytics/USAGE
  google_analytics/__init__.py
  google_analytics/migrations/
  google_analytics/migrations/0001_initial.py
  google_analytics/migrations/__init__.py
  google_analytics/models.py
  google_analytics/templates/
  google_analytics/templates/google_analytics/
  google_analytics/templates/google_analytics/analytics_template.html
  google_analytics/templatetags/
  google_analytics/templatetags/__init__.py
  google_analytics/templatetags/analytics.py
modified:
  lava_server/settings/common.py
  lava_server/templates/layouts/base.html


--
lp:lava-server
https://code.launchpad.net/~linaro-validation/lava-server/trunk

You are subscribed to branch lp:lava-server.
To unsubscribe from this branch go to https://code.launchpad.net/~linaro-validation/lava-server/trunk/+edit-subscription
diff mbox

Patch

=== added directory 'google_analytics'
=== added file 'google_analytics/LICENSE'
--- google_analytics/LICENSE	1970-01-01 00:00:00 +0000
+++ google_analytics/LICENSE	2013-07-22 17:01:41 +0000
@@ -0,0 +1,27 @@ 
+Copyright (c) 2008, Clint Ecker
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without 
+modification, are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this 
+list of conditions and the following disclaimer.
+
+Redistributions in binary form must reproduce the above copyright notice, this
+list of conditions and the following disclaimer in the documentation and/or 
+other materials provided with the distribution.
+
+Neither the name of the <ORGANIZATION> nor the names of its contributors may 
+be used to endorse or promote products derived from this software without 
+specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file

=== added file 'google_analytics/USAGE'
--- google_analytics/USAGE	1970-01-01 00:00:00 +0000
+++ google_analytics/USAGE	2013-07-22 17:01:41 +0000
@@ -0,0 +1,51 @@ 
+I manage a lot of Django projects that present slightly-different forms to 
+users depending on the site/domain they're visiting.  There's also a bunch of 
+custom submission code that differs from form to form, but that's neither here
+nor there.
+
+I need different Google Analytics codes depending on the sites and after 
+sticking these tags into every single template, I thought it would be cool to 
+be able to manage these Google analytics accounts from the Django admin page. 
+I also added a mode of operation that excludes the admin interface altogether 
+(you can just use the template tag)
+
+==Two modes of operation==
+
+Administering and associating codes with Django sites
+---------------------------------------------------------
+1. Add the `google_analytics` application to your `INSTALLED_APPS` 
+		section of your `settings.py`.  This mode requires that you be using 
+		the Django sites framework too, so make sure you have that set up as 
+		well.
+
+2. Add `GOOGLE_ANALYTICS_MODEL = True` to your `settings.py` 
+
+3. Run a `./manage.py syncdb` to add the database tables
+
+4. Go to your project's admin page (usually `/admin/`) and click into a site 
+		objects
+
+5. You'll now see a new field under the normal site information called 
+		"Analytics Code". In this box you put your unique analytics code for 
+		your project's domain.  It looks like `UA-xxxxxx-x` and save the site.
+
+6. In your base template (usually a `base.html`) insert this tag at the very 
+		top: `{% load analytics %}`
+
+7. In the same template, insert the following code right before the closing 
+		body tag: `{% analytics %}`
+
+
+
+===Just using the template tag===
+
+1. Add the `google_analytics` application to your `INSTALLED_APPS` section of
+ 		your `settings.py`.
+
+2. In your base template, usually a `base.html`, insert this tag at the very 
+		top: `{% load analytics %}`
+
+3. In the same template, insert the following code right before the closing 
+		body tag: `{% analytics "UA-xxxxxx-x" %}` the `UA-xxxxxx-x` is a 
+		unique Google Analytics code for you domain when you sign up for a new
+		account.

=== added file 'google_analytics/__init__.py'
=== added directory 'google_analytics/migrations'
=== added file 'google_analytics/migrations/0001_initial.py'
--- google_analytics/migrations/0001_initial.py	1970-01-01 00:00:00 +0000
+++ google_analytics/migrations/0001_initial.py	2013-07-22 17:01:41 +0000
@@ -0,0 +1,40 @@ 
+# -*- coding: utf-8 -*-
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        # Adding model 'Analytic'
+        db.create_table('google_analytics_analytic', (
+            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('site', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['sites.Site'], unique=True)),
+            ('analytics_code', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)),
+        ))
+        db.send_create_signal('google_analytics', ['Analytic'])
+
+
+    def backwards(self, orm):
+        # Deleting model 'Analytic'
+        db.delete_table('google_analytics_analytic')
+
+
+    models = {
+        'google_analytics.analytic': {
+            'Meta': {'object_name': 'Analytic'},
+            'analytics_code': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']", 'unique': 'True'})
+        },
+        'sites.site': {
+            'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
+            'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        }
+    }
+
+    complete_apps = ['google_analytics']
\ No newline at end of file

=== added file 'google_analytics/migrations/__init__.py'
=== added file 'google_analytics/models.py'
--- google_analytics/models.py	1970-01-01 00:00:00 +0000
+++ google_analytics/models.py	2013-07-23 12:14:04 +0000
@@ -0,0 +1,19 @@ 
+from django.db import models
+from django.conf import settings
+from django.contrib.sites.admin import SiteAdmin
+from django.contrib.sites.models import Site
+from django.contrib import admin
+
+if getattr(settings, 'GOOGLE_ANALYTICS_MODEL', False):
+
+    class Analytic(models.Model):
+        site = models.ForeignKey(Site, unique=True)
+        analytics_code = models.CharField(blank=True, max_length=100)
+
+        def __unicode__(self):
+            return u"%s" % (self.analytics_code)
+
+    class AnalyticAdmin(admin.ModelAdmin):
+        list_display = ('site', 'analytics_code',)
+
+    admin.site.register(Analytic, AnalyticAdmin)

=== added directory 'google_analytics/templates'
=== added directory 'google_analytics/templates/google_analytics'
=== added file 'google_analytics/templates/google_analytics/analytics_template.html'
--- google_analytics/templates/google_analytics/analytics_template.html	1970-01-01 00:00:00 +0000
+++ google_analytics/templates/google_analytics/analytics_template.html	2013-07-24 11:50:02 +0000
@@ -0,0 +1,17 @@ 
+<script>
+  (
+  function(i,s,o,g,r,a,m) {
+    i['GoogleAnalyticsObject']=r;
+    i[r]=i[r]||function() {
+      (i[r].q=i[r].q||[]).push(arguments)
+    }, i[r].l=1*new Date();
+  a=s.createElement(o),
+  m=s.getElementsByTagName(o)[0];
+  a.async=1;
+  a.src=g;
+  m.parentNode.insertBefore(a,m)
+  }) (window,document,'script','//www.google-analytics.com/analytics.js','ga');
+
+  ga('create', '{{ analytics_code }}', '{{domain}}');
+  ga('send', 'pageview');
+</script>

=== added directory 'google_analytics/templatetags'
=== added file 'google_analytics/templatetags/__init__.py'
=== added file 'google_analytics/templatetags/analytics.py'
--- google_analytics/templatetags/analytics.py	1970-01-01 00:00:00 +0000
+++ google_analytics/templatetags/analytics.py	2013-07-24 11:50:02 +0000
@@ -0,0 +1,55 @@ 
+from django import template
+from django.db import models
+from django.contrib.sites.models import Site
+
+from django.template import Context, loader
+
+
+register = template.Library()
+Analytics = models.get_model('google_analytics', 'analytic')
+
+def do_get_analytics(parser, token):
+    try:
+        # split_contents() knows not to split quoted strings.
+        tag_name, code = token.split_contents()
+    except ValueError:
+        code = None
+
+    if not code:
+        current_site = Site.objects.get_current()
+    else:
+        if not (code[0] == code[-1] and code[0] in ('"', "'")):
+            raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
+        code = code[1:-1]
+        current_site = None
+    return AnalyticsNode(current_site, code)
+
+class AnalyticsNode(template.Node):
+    def __init__(self, site=None, code=None):
+        self.site = site
+        self.code = code
+
+    def render(self, context):
+        content = ''
+        if self.site:
+            code_set = Analytics.objects.filter(site=self.site)
+            if code_set:
+                code = code_set[0].analytics_code
+            else:
+                return ''
+        elif self.code:
+            code = self.code
+        else:
+            return ''
+
+        if code.strip() != '':
+            t = loader.get_template('google_analytics/analytics_template.html')
+            c = Context({
+                'analytics_code': code,
+                'domain': '.'.join(self.site.domain.split('.')[2:])
+            })
+            return t.render(c)
+        else:
+            return ''
+
+register.tag('analytics', do_get_analytics)

=== modified file 'lava_server/settings/common.py'
--- lava_server/settings/common.py	2013-07-11 11:26:54 +0000
+++ lava_server/settings/common.py	2013-07-25 12:07:17 +0000
@@ -122,6 +122,7 @@ 
     'south',
     # Uncomment to enable Atlassian Crowd auth support.
     #'crowdrest',
+    'google_analytics',
 ]
 
 try:
@@ -168,6 +169,9 @@ 
 
 RESTRUCTUREDTEXT_FILTER_SETTINGS = {"initial_header_level": 4}
 
+# Add google analytics model.
+GOOGLE_ANALYTICS_MODEL = True
+
 # Skip south tests as they seem to break everything else.
 # This is fixed in south 0.7.1, if we upgrade past that it's safe to
 # remove this line.

=== modified file 'lava_server/templates/layouts/base.html'
--- lava_server/templates/layouts/base.html	2012-09-20 20:58:20 +0000
+++ lava_server/templates/layouts/base.html	2013-07-24 10:06:01 +0000
@@ -1,3 +1,4 @@ 
+{% load analytics %}
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" lang="{{ LANGUAGE_CODE }}" xml:lang="{{ LANGUAGE_CODE }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}>
   <head>
@@ -15,6 +16,7 @@ 
     {% block extrahead %}{% endblock %}
   </head>
   <body>
+    {% analytics %}
     {% block body %}
     {% endblock %}
   </body>