Forked mumble-django project from https://bitbucket.org/Svedrin/mumble-django
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

389 lines
14 KiB

  1. # -*- coding: utf-8 -*-
  2. # kate: space-indent on; indent-width 4; replace-tabs on;
  3. """
  4. * Copyright (C) 2010, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
  5. *
  6. * djExtDirect is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This package is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. """
  16. try:
  17. import simplejson
  18. except ImportError:
  19. import json as simplejson
  20. import functools
  21. from django import forms
  22. from django.http import HttpResponse, Http404
  23. from django.conf.urls.defaults import url
  24. from django.utils.safestring import mark_safe
  25. from django.core.serializers.json import DjangoJSONEncoder
  26. from provider import Provider
  27. # Template used for the auto-generated form classes
  28. EXT_CLASS_TEMPLATE = """
  29. Ext.namespace('Ext.ux');
  30. Ext.ux.%(clsname)s = function( config ){
  31. Ext.apply( this, config );
  32. Ext.applyIf( this, {
  33. defaults: { "anchor": "-20px" },
  34. paramsAsHash: true,
  35. baseParams: {},
  36. autoScroll: true,
  37. submitButtonText: "Submit"
  38. } );
  39. Ext.applyIf( this, {
  40. buttons: [{
  41. text: this.submitButtonText,
  42. handler: this.submit,
  43. id: '%(clsname)s_submit',
  44. scope: this
  45. }]
  46. });
  47. var defaultconf = %(defaultconf)s;
  48. Ext.applyIf( this, defaultconf );
  49. this.initialConfig = defaultconf;
  50. this.api = %(apiconf)s;
  51. for( var i = 0; i < this.items.length; i++ ){
  52. if( this.items[i].xtype == "choicescombo" ){
  53. this.items[i].pk = config.pk;
  54. this.items[i].api = this.api;
  55. }
  56. }
  57. Ext.ux.%(clsname)s.superclass.constructor.call( this );
  58. this.form.api = this.api;
  59. this.form.paramsAsHash = true;
  60. if( typeof config.pk != "undefined" ){
  61. this.load();
  62. }
  63. this.form.addEvents({
  64. 'submitSuccess': true,
  65. 'submitFailure': true
  66. });
  67. if( typeof config.listeners != "undefined" ){
  68. if( typeof config.listeners.submitSuccess != "undefined" )
  69. this.form.on("submitSuccess", config.listeners.submitSuccess);
  70. if( typeof config.listeners.submitFailure != "undefined" )
  71. this.form.on("submitFailure", config.listeners.submitFailure);
  72. }
  73. }
  74. Ext.extend( Ext.ux.%(clsname)s, Ext.form.FormPanel, {
  75. load: function(){
  76. this.getForm().load({ params: Ext.applyIf( {pk: this.pk}, this.baseParams ) });
  77. },
  78. submit: function(){
  79. this.getForm().submit({
  80. params: Ext.applyIf( {pk: this.pk}, this.baseParams ),
  81. failure: function( form, action ){
  82. if( action.failureType == Ext.form.Action.SERVER_INVALID &&
  83. typeof action.result.errors['__all__'] != 'undefined' ){
  84. Ext.Msg.alert( "Error", action.result.errors['__all__'] );
  85. }
  86. form.fireEvent("submitFailure", form, action);
  87. },
  88. success: function( form, action ){
  89. form.fireEvent("submitSuccess", form, action);
  90. }
  91. });
  92. },
  93. } );
  94. Ext.reg( '%(clslowername)s', Ext.ux.%(clsname)s );
  95. """
  96. # About the this.form.* lines, see
  97. # http://www.sencha.com/forum/showthread.php?96001-solved-Ext.Direct-load-data-in-extended-Form-fails-%28scope-issue%29
  98. EXT_DYNAMICCHOICES_COMBO = """
  99. Ext.namespace('Ext.ux');
  100. Ext.ux.ChoicesCombo = function( config ){
  101. Ext.apply( this, config );
  102. Ext.applyIf( this, {
  103. displayField: this.name,
  104. valueField: this.name,
  105. hiddenName: this.name,
  106. autoSelect: false,
  107. typeAhead: true,
  108. emptyText: 'Select...',
  109. triggerAction: 'all',
  110. selectOnFocus: true,
  111. });
  112. this.triggerAction = 'all';
  113. this.store = new Ext.data.DirectStore({
  114. baseParams: {'pk': this.pk, 'field': this.name},
  115. directFn: this.api.choices,
  116. paramOrder: ['pk', 'field'],
  117. reader: new Ext.data.JsonReader({
  118. successProperty: 'success',
  119. idProperty: this.valueField,
  120. root: 'data',
  121. fields: [this.valueField, this.displayField]
  122. })
  123. });
  124. Ext.ux.ChoicesCombo.superclass.constructor.call( this );
  125. this.store.load();
  126. };
  127. Ext.extend( Ext.ux.ChoicesCombo, Ext.form.ComboBox, {
  128. });
  129. Ext.reg( 'choicescombo', Ext.ux.ChoicesCombo );
  130. """
  131. class FormProvider(Provider):
  132. """ This class extends the provider class to handle Django forms.
  133. To export a form, register it using the ``register_form`` decorator.
  134. After registration, you will be able to retrieve an ExtJS form class
  135. definition for this form under the URL "<formname>.js". Include this
  136. script via a <script> tag just like the "api.js" for Ext.Direct.
  137. The form class will then be created as Ext.ux.<FormName> and will
  138. have a registered xtype of "formname".
  139. When registering a form, the Provider will automatically generate and
  140. export objects and methods for data transfer, so the form will be
  141. ready to use.
  142. To ensure that validation error messages are displayed properly, be
  143. sure to call Ext.QuickTips.init() somewhere in your code.
  144. In order to do extra validation, the Provider checks if your form class
  145. has a method called EXT_validate, and if so, calls that method with the
  146. request as parameter before calling is_valid() or save(). If EXT_validate
  147. returns False, the form will not be saved and an error will be returned
  148. instead. EXT_validate should update form.errors before returning False.
  149. """
  150. def __init__( self, name="Ext.app.REMOTING_API", autoadd=True ):
  151. Provider.__init__( self, name="Ext.app.REMOTING_API", autoadd=True )
  152. self.forms = {}
  153. def get_choices_combo_src( self, request ):
  154. return HttpResponse( EXT_DYNAMICCHOICES_COMBO, mimetype="text/javascript" )
  155. def register_form( self, formclass ):
  156. """ Register a Django Form class. """
  157. if not issubclass( formclass, forms.ModelForm ):
  158. raise TypeError( "Ext.Direct provider can only handle ModelForms, '%s' is something else." % formclass.__name__ )
  159. formname = formclass.__name__.lower()
  160. self.forms[formname] = formclass
  161. getfunc = functools.partial( self.get_form_data, formname )
  162. getfunc.EXT_len = 1
  163. getfunc.EXT_argnames = ["pk"]
  164. getfunc.EXT_flags = {}
  165. updatefunc = functools.partial( self.update_form_data, formname )
  166. updatefunc.EXT_len = 1
  167. updatefunc.EXT_argnames = ["pk"]
  168. updatefunc.EXT_flags = { 'formHandler': True }
  169. choicesfunc = functools.partial( self.get_field_choices, formname )
  170. choicesfunc.EXT_len = 2
  171. choicesfunc.EXT_argnames = ["pk", "field"]
  172. choicesfunc.EXT_flags = {}
  173. self.classes["XD_%s" % formclass.__name__] = {
  174. "get": getfunc,
  175. "update": updatefunc,
  176. "choices": choicesfunc,
  177. }
  178. return formclass
  179. def get_form( self, request, formname ):
  180. """ Convert the form given in "formname" to an ExtJS FormPanel. """
  181. if formname not in self.forms:
  182. raise Http404(formname)
  183. items = []
  184. clsname = self.forms[formname].__name__
  185. hasfiles = False
  186. for fldname in self.forms[formname].base_fields:
  187. field = self.forms[formname].base_fields[fldname]
  188. extfld = {
  189. "fieldLabel": field.label is not None and unicode(field.label) or fldname,
  190. "name": fldname,
  191. "xtype": "textfield",
  192. #"allowEmpty": field.required,
  193. }
  194. if hasattr( field, "choices" ):
  195. if field.choices:
  196. # Static choices dict
  197. extfld.update({
  198. "name": fldname,
  199. "hiddenName": fldname,
  200. "xtype": "combo",
  201. "store": field.choices,
  202. "typeAhead": True,
  203. "emptyText": 'Select...',
  204. "triggerAction": 'all',
  205. "selectOnFocus": True,
  206. })
  207. else:
  208. # choices set but empty - load them dynamically when pk is known
  209. extfld.update({
  210. "name": fldname,
  211. "xtype": "choicescombo",
  212. "displayField": "v",
  213. "valueField": "k",
  214. })
  215. pass
  216. elif isinstance( field, forms.BooleanField ):
  217. extfld.update({
  218. "xtype": "checkbox"
  219. })
  220. elif isinstance( field, forms.IntegerField ):
  221. extfld.update({
  222. "xtype": "numberfield",
  223. })
  224. elif isinstance( field, forms.FileField ) or isinstance( field, forms.ImageField ):
  225. hasfiles = True
  226. extfld.update({
  227. "xtype": "textfield",
  228. "inputType": "file"
  229. })
  230. elif isinstance( field.widget, forms.Textarea ):
  231. extfld.update({
  232. "xtype": "textarea",
  233. "grow": True
  234. })
  235. elif isinstance( field.widget, forms.PasswordInput ):
  236. extfld.update({
  237. "xtype": "textfield",
  238. "inputType": "password"
  239. })
  240. items.append( extfld )
  241. if field.help_text:
  242. items.append({
  243. "xtype": "label",
  244. "text": unicode(field.help_text),
  245. "cls": "form_hint_label",
  246. })
  247. clscode = EXT_CLASS_TEMPLATE % {
  248. 'clsname': clsname,
  249. 'clslowername': formname,
  250. 'defaultconf': '{'
  251. 'items:' + simplejson.dumps(items, cls=DjangoJSONEncoder, indent=4) + ','
  252. 'fileUpload: ' + simplejson.dumps(hasfiles, cls=DjangoJSONEncoder) + ','
  253. '}',
  254. 'apiconf': ('{'
  255. 'load: ' + ("XD_%s.get" % clsname) + ","
  256. 'submit:' + ("XD_%s.update" % clsname) + ","
  257. 'choices:' + ("XD_%s.choices" % clsname) + ","
  258. "}"),
  259. }
  260. return HttpResponse( mark_safe( clscode ), mimetype="text/javascript" )
  261. def get_field_choices( self, formname, request, pk, field ):
  262. """ Create a bound instance of the form and return choices from the given field. """
  263. formcls = self.forms[formname]
  264. if pk != -1:
  265. instance = formcls.Meta.model.objects.get( pk=pk )
  266. else:
  267. instance = None
  268. forminst = formcls( instance=instance )
  269. return {
  270. 'success': True,
  271. 'data': [ {'k': c[0], 'v': c[1]} for c in forminst.fields[field].choices ]
  272. }
  273. def get_form_data( self, formname, request, pk ):
  274. """ Called to get the current values when a form is to be displayed. """
  275. formcls = self.forms[formname]
  276. if pk != -1:
  277. instance = formcls.Meta.model.objects.get( pk=pk )
  278. else:
  279. instance = None
  280. forminst = formcls( instance=instance )
  281. if hasattr( forminst, "EXT_authorize" ) and \
  282. forminst.EXT_authorize( request, "get" ) is False:
  283. return { 'success': False, 'errors': {'__all__': 'access denied'} }
  284. data = {}
  285. for fld in forminst.fields:
  286. if instance:
  287. data[fld] = getattr( instance, fld )
  288. else:
  289. data[fld] = forminst.base_fields[fld].initial
  290. return { 'data': data, 'success': True }
  291. def update_form_data( self, formname, request ):
  292. """ Called to update the underlying model when a form has been submitted. """
  293. pk = int(request.POST['pk'])
  294. formcls = self.forms[formname]
  295. if pk != -1:
  296. instance = formcls.Meta.model.objects.get( pk=pk )
  297. else:
  298. instance = None
  299. if request.POST['extUpload'] == "true":
  300. forminst = formcls( request.POST, request.FILES, instance=instance )
  301. else:
  302. forminst = formcls( request.POST, instance=instance )
  303. if hasattr( forminst, "EXT_authorize" ) and \
  304. forminst.EXT_authorize( request, "update" ) is False:
  305. return { 'success': False, 'errors': {'__all__': 'access denied'} }
  306. # save if either no usable validation method available or validation passes; and form.is_valid
  307. if ( hasattr( forminst, "EXT_validate" ) and callable( forminst.EXT_validate )
  308. and not forminst.EXT_validate( request ) ):
  309. return { 'success': False, 'errors': {'__all__': 'pre-validation failed'} }
  310. if forminst.is_valid():
  311. forminst.save()
  312. return { 'success': True }
  313. else:
  314. errdict = {}
  315. for errfld in forminst.errors:
  316. errdict[errfld] = "\n".join( forminst.errors[errfld] )
  317. return { 'success': False, 'errors': errdict }
  318. def get_urls(self):
  319. """ Return the URL patterns. """
  320. pat = Provider.get_urls(self)
  321. if self.forms:
  322. pat.append( url( r'choicescombo.js$', self.get_choices_combo_src ) )
  323. pat.append( url( r'(?P<formname>\w+).js$', self.get_form ) )
  324. return pat
  325. urls = property(get_urls)