URL: show qrcode for URL in admin (using google charts)
authorTero Marttila <terom@fixme.fi>
Mon, 15 Jul 2013 02:34:23 +0300
changeset 4 d56f48f6c94b
parent 3 e7d3f1a28b24
child 5 8c15ae21309f
URL: show qrcode for URL in admin (using google charts)
qrurls/admin.py
qrurls/models.py
--- a/qrurls/admin.py	Mon Jul 15 01:51:59 2013 +0300
+++ b/qrurls/admin.py	Mon Jul 15 02:34:23 2013 +0300
@@ -1,13 +1,32 @@
 from django.contrib import admin
 from qrurls.models import URL, URLItem
+import django.utils.html
 
 class URLItemInline (admin.TabularInline) :
     model = URLItem
 
 class URLAdmin (admin.ModelAdmin) :
+    def qrcode_img (self, obj) :
+        return '<img src="{img}" />'.format(
+                img=django.utils.html.escape(obj.qrcode_img()),
+        )
+    qrcode_img.allow_tags = True
+
+    readonly_fields = (
+        'qrcode_url',
+        'qrcode_img',
+    )
     list_display = (
         'shorturl',
     )
+    fieldsets = (
+        (None, {
+            'fields': ('shorturl', )
+        }),
+        ("QRCode", {
+            'fields': ('qrcode_url', 'qrcode_img', ),
+        }),
+    )
     inlines = (URLItemInline, )
 
 class URLItemAdmin (admin.ModelAdmin) :
--- a/qrurls/models.py	Mon Jul 15 01:51:59 2013 +0300
+++ b/qrurls/models.py	Mon Jul 15 02:34:23 2013 +0300
@@ -1,5 +1,9 @@
 from django.db import models
 from django.core.urlresolvers import reverse
+import django.utils.http
+from django.contrib.sites.models import get_current_site
+
+QRCODE_API = 'https://chart.googleapis.com/chart?cht=qr&chs={width}x{height}&chl={url}'
 
 class URL(models.Model):
     shorturl = models.SlugField(unique=True)
@@ -8,6 +12,18 @@
         verbose_name = u"URL"
         verbose_name_plural = u"URLs"
 
+    def qrcode_img (self, size=512) :
+        return QRCODE_API.format(
+                width=size, height=size,
+                url=django.utils.http.urlquote(self.qrcode_url()),
+        )
+
+    def qrcode_url (self) :
+        return 'http://{domain}{url}'.format(
+                domain = get_current_site(None).domain,
+                url = self.get_absolute_url(),
+        )
+
     def get_absolute_url (self) :
         return reverse('shorturl', args=[self.shorturl])