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.

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