# -*- coding: utf-8 -*- # kate: space-indent on; indent-width 4; replace-tabs on; """ * Copyright (C) 2010, Michael "Svedrin" Ziegler * * djExtDirect is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This package is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. """ import simplejson import inspect import functools import traceback from sys import stderr from django import forms from django.http import HttpResponse, Http404 from django.conf import settings from django.conf.urls.defaults import patterns, url from django.core.urlresolvers import reverse from django.utils.datastructures import MultiValueDictKeyError from django.views.decorators.csrf import csrf_exempt from django.utils.safestring import mark_safe __author__ = "Michael Ziegler" __copyright__ = "Copyright (C) 2010, Michael Ziegler" __license__ = "GPL" __version__ = "0.1" __email__ = "diese-addy@funzt-halt.net" __status__ = "Development" def getname( cls_or_name ): if type(cls_or_name) not in ( str, unicode ): return cls_or_name.__name__ return cls_or_name # Template used for the auto-generated form classes EXT_CLASS_TEMPLATE = """ Ext.namespace('Ext.ux'); Ext.ux.%(clsname)s = function( config ){ Ext.apply( this, config ); var defaultconf = %(defaultconf)s; Ext.applyIf( this, defaultconf ); this.initialConfig = defaultconf; Ext.ux.%(clsname)s.superclass.constructor.call( this ); this.form.api = %(apiconf)s; this.form.paramsAsHash = true; if( typeof config.pk != "undefined" ){ this.load(); } } Ext.extend( Ext.ux.%(clsname)s, Ext.form.FormPanel, { load: function(){ this.getForm().load({ params: Ext.applyIf( {pk: this.pk}, this.baseParams ) }); }, submit: function(){ this.getForm().submit({ params: Ext.applyIf( {pk: this.pk}, this.baseParams ), failure: function( form, action ){ if( action.failureType == Ext.form.Action.SERVER_INVALID && typeof action.result.errors[''] != 'undefined' ){ Ext.Msg.alert( "Error", action.result.errors[''] ); } } }); }, } ); Ext.reg( '%(clslowername)s', Ext.ux.%(clsname)s ); """ # About the this.form.* lines, see # http://www.sencha.com/forum/showthread.php?96001-solved-Ext.Direct-load-data-in-extended-Form-fails-%28scope-issue%29 class Provider( object ): """ Provider for Ext.Direct. This class handles building API information and routing requests to the appropriate functions, and serializing their response and exceptions - if any. Instantiation: >>> EXT_JS_PROVIDER = Provider( [name="Ext.app.REMOTING_API", autoadd=True] ) If autoadd is True, the api.js will include a line like such:: Ext.Direct.addProvider( Ext.app.REMOTING_API ); After instantiating the Provider, register functions to it like so: >>> @EXT_JS_PROVIDER.register_method("myclass") ... def myview( request, possibly, some, other, arguments ): ... " does something with all those args and returns something " ... return 13.37 Note that those views **MUST NOT** return an HttpResponse but simply the plain result, as the Provider will build a response from whatever your view returns! To be able to access the Provider, include its URLs in an arbitrary URL pattern, like so: >>> from views import EXT_JS_PROVIDER # import our provider instance >>> urlpatterns = patterns( ... # other patterns go here ... ( r'api/', include(EXT_DIRECT_PROVIDER.urls) ), ... ) This way, the Provider will define the URLs "api/api.js" and "api/router". If you then access the "api/api.js" URL, you will get a response such as:: Ext.app.REMOTING_API = { # Ext.app.REMOTING_API is from Provider.name "url": "/mumble/api/router", "type": "remoting", "actions": {"myclass": [{"name": "myview", "len": 4}]} } You can then use this code in ExtJS to define the Provider there. """ def __init__( self, name="Ext.app.REMOTING_API", autoadd=True ): self.name = name self.autoadd = autoadd self.classes = {} self.forms = {} def register_method( self, cls_or_name, flags={} ): """ Return a function that takes a method as an argument and adds that to cls_or_name. The flags parameter is for additional information, e.g. formHandler=True. Note: This decorator does not replace the method by a new function, it returns the original function as-is. """ return functools.partial( self._register_method, cls_or_name, flags=flags ) def _register_method( self, cls_or_name, method, flags={} ): """ Actually registers the given function as a method of cls_or_name. """ clsname = getname(cls_or_name) if clsname not in self.classes: self.classes[clsname] = {} self.classes[ clsname ][ method.__name__ ] = method method.EXT_argnames = inspect.getargspec( method ).args[1:] method.EXT_len = len( method.EXT_argnames ) method.EXT_flags = flags return method def register_form( self, formclass ): """ Register a Django Form class. After registration, you will be able to retrieve an ExtJS form class definition for this form under the URL ".js". Include this script via a