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.

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