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.

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