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.

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