summaryrefslogtreecommitdiff
path: root/sublab_project/preview_admin/admin.py
blob: d7afd998c8d40a8fd518c423294c0f0df320b2c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from django.contrib.admin import ModelAdmin
from django.conf.urls.defaults import patterns, url
from django.core.urlresolvers import reverse, NoReverseMatch
from django.shortcuts import render_to_response
from django.utils.safestring import mark_safe
from django.conf import settings
from django.http import Http404

import logging
logger = logging.getLogger('preview_admin')

class PreviewAdmin(ModelAdmin):
    preview_fields = {}
    def get_urls(self):
        info = self.model._meta.app_label, self.model._meta.module_name

        urls = super(PreviewAdmin, self).get_urls()
        myurls = patterns('',
                url(r'^preview/(.+)/$', self.admin_site.admin_view(self.preview),
                    name='%s_%s_preview' % info),
        )
        return myurls + urls

    def add_preview(self, fieldname, formfield):
        render = formfield.widget.render

        def preview_render(name, *args, **kwargs):
            rendered = render(name, *args, **kwargs)

            info = self.model._meta.app_label, self.model._meta.module_name
            preview_url = reverse('admin:%s_%s_preview' % info,
                        args=[name], current_app=self.admin_site.name)

            rendered += '<div id="preview-%s" class="preview-box"></div>' % fieldname
            rendered += '<p><a onclick="preview_admin(\'%s\',\'%s\')">Preview</a></p>' % (
                    fieldname, preview_url)
            return mark_safe(rendered)

        formfield.widget.render = preview_render

    def formfield_for_dbfield(self, db_field, **kwargs):
        formfield = super(PreviewAdmin, self).formfield_for_dbfield(db_field, **kwargs)

        if db_field.name in self.preview_fields:
            self.add_preview(db_field.name, formfield)

        return formfield

    def preview(self, request, field):
        if (field not in self.preview_fields
                or 'data' not in request.GET):
            raise Http404

        context = {
                'preview' : mark_safe(self.preview_fields[field](request.GET['data']))
        }
        return render_to_response('admin/preview.html', context)

    def _media(self):
        media = super(PreviewAdmin, self)._media()
        media.add_js(['%sjs/jquery.js' % settings.ADMIN_MEDIA_PREFIX ])
        media.add_js(['%sjs/preview.js' % settings.ADMIN_MEDIA_PREFIX ])
        media.add_css({
            'all' : ['%scss/preview.css' % settings.ADMIN_MEDIA_PREFIX ]})

        return media
    media = property(_media)