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.

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