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.

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