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 += '
' % fieldname rendered += '' % ( 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)