Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

getExtJsModelForm : auto clean DateTime,Date and Time fields

Grids : add verbose_name to column header, fix errors on date/times, add default renderer when field has choices
  • Loading branch information...
commit 9381bbb504f1d6aee1cd70ab26fd3d1dcec205b6 1 parent e4a57bb
@revolunet authored
Showing with 65 additions and 21 deletions.
  1. +28 −5 forms.py
  2. +31 −16 grids.py
  3. +6 −0 static/js/Ext.ux.AutoEditableGrid.js
View
33 forms.py
@@ -8,6 +8,19 @@
import utils
+
+def DateField_ExtJs_clean(value):
+ value = value.split('T')[0]
+ return value
+
+def DateTimeField_ExtJs_clean(value):
+ value = value.replace('T', ' ')
+ return value
+
+def TimeField_ExtJs_clean(value):
+ #value = value.split('T')[1]
+ return value
+
def getExtJsModelForm(modelref, exclude_list = [], fields_list = []):
class FormFromModel(forms.ModelForm):
class Meta:
@@ -15,9 +28,17 @@ class Meta:
exclude = exclude_list
fields = fields_list
def __init__(self, *args, **kwargs):
- #print args, kwargs
super(FormFromModel, self).__init__(*args, **kwargs)
- # todo : autoclean for date / time fields
+
+ ExtJsForm.addto(FormFromModel)
+
+ # override Field.clean for date fields and ExtJs formats
+ for item in FormFromModel.base_fields:
+ #print 'class field', item, FormFromModel.base_fields[item]
+ o = FormFromModel.base_fields[item]
+ if o.__class__.__name__ in ['DateField','DateTimeField','TimeField']:
+ o.clean = globals()['%s_ExtJs_clean' % o.__class__.__name__]
+
return FormFromModel
def getFieldConfig(field_name, django_field, value = None):
@@ -44,6 +65,7 @@ def getFieldConfig(field_name, django_field, value = None):
e = getattr(ofield, 'widget', None)
if e:
+ #print 'e', e
s = ofield.widget.attrs.get('style', None)
if s:
config['style'] = s
@@ -55,7 +77,7 @@ def getFieldConfig(field_name, django_field, value = None):
- #print field_name, field_class_name
+ # print field_name, field_class_name
if field_class_name == 'HiddenInput':
config['xtype'] = 'hidden'
@@ -112,9 +134,11 @@ def getFieldConfig(field_name, django_field, value = None):
elif field_class_name == 'DateField':
config['xtype'] = 'datefield'
config['format'] = utils.DateFormatConverter(to_extjs = form_field.input_formats[0])
+ #config['hiddenFormat'] = utils.DateFormatConverter(to_extjs = form_field.input_formats[0])
elif field_class_name == 'TimeField':
config['xtype'] = 'timefield'
config['increment'] = 30
+ # config['hiddenFormat'] = utils.DateFormatConverter(to_extjs = form_field.input_formats[0])
config['format'] = utils.DateFormatConverter(to_extjs = form_field.input_formats[0])
config['width'] = 60
config['value'] = value and value.strftime(ofield.input_formats[0]) or ''
@@ -170,6 +194,7 @@ def __init__(self, field_name, django_field):
if django_field.initial:
self.config['value'] = django_field.initial
# apply html style if any
+ #print django_field.widget
s = django_field.widget.attrs.get('style', None)
if s:
self.config['style'] = s
@@ -206,8 +231,6 @@ def addto(self, cls):
handler_submit = "function(btn) {console.log(this, btn);this.findParentByType(this.form_xtype).submitForm()}"
handler_reset = "function(btn) {console.log(this, btn);this.findParentByType(this.form_xtype).resetForm()}"
cls.ext_baseConfig = {
-
-
}
@staticmethod
View
47 grids.py
@@ -65,30 +65,46 @@ def __init__(self, model):
self.fields.append(self.Meta.fields_conf[field.name])
continue
fdict = {'name':field.name, 'header': field.name}
+
+ if getattr(field, 'verbose_name', None) and field.verbose_name != field.name:
+ fdict['tooltip'] = u'%s' % field.verbose_name
+
if field.name == 'id':
fdict['id']='id'
if field.__class__.__name__ == 'DateTimeField':
fdict['type'] = 'datetime'
+ fdict['xtype'] = 'datecolumn'
fdict['dateFormat'] = 'Y-m-d H:i:s'
fdict['format'] = 'Y-m-d H:i:s'
+
#fdict['editor'] = "new Ext.ux.form.DateTime({hiddenFormat:'Y-m-d H:i', dateFormat:'Y-m-D', timeFormat:'H:i'})"
if field.__class__.__name__ == 'DateField':
fdict['type'] = 'date'
+ fdict['xtype'] = 'datecolumn'
fdict['dateFormat'] = 'Y-m-d'
fdict['format'] = 'Y-m-d'
+ #fdict['renderer'] = 'Ext.util.'
#fdict['editor'] = "new Ext.form.DateField({format:'Y-m-d'})"
elif field.__class__.__name__ == 'IntegerField':
- fdict['type'] = 'int'
+ fdict['xtype'] = 'numbercolumn'
#fdict['editor'] = 'new Ext.form.NumberField()'
elif field.__class__.__name__ == 'BooleanField':
- fdict['type'] = 'boolean'
+ fdict['xtype'] = 'booleancolumn'
#fdict['editor'] = 'new Ext.form.Checkbox()'
elif field.__class__.__name__ == 'DecimalField':
- fdict['type'] = 'float'
+ fdict['xtype'] = 'numbercolumn '
fdict['renderer'] = 'function(v) {return (v.toFixed && v.toFixed(2) || 0);}'
#fdict['editor'] = 'new Ext.form.NumberField()'
elif field.__class__.__name__ == 'ForeignKey':
pass
+ # renderer : display FK str
+ # choices
+ elif field.choices:
+ #print 'FIELD CHOICES', field.choices
+ a = {}
+ for c in field.choices:
+ a[c[0]] = c[1]
+ fdict['renderer'] = 'function(v) {a = %s; return a[v] || "";}' % utils.JSONserialise(a)
if getattr(self.Meta, 'fields_conf', {}).has_key(field.name):
fdict.update(self.Meta.fields_conf[field.name])
@@ -149,9 +165,9 @@ def get_rows(self, fields, queryset, start, limit):
val = getattr(item, field['name'], '')
if val:
if field.get('type', '') == 'date':
- val = val.strftime(utils.DateFormatConverter(to_python = field['dateFormat'] ) )
+ val = val.strftime(utils.DateFormatConverter(to_python = field['format'] ) )
elif field.get('type', '') == 'datetime':
- val = val.strftime(utils.DateFormatConverter(to_python = field['dateFormat'] ) )
+ val = val.strftime(utils.DateFormatConverter(to_python = field['format'] ) )
else:
val = utils.JsonCleanstr(val)
else:
@@ -219,8 +235,12 @@ def __init__(self, *args, **kwargs):
# add editors
for field in self.base_fields:
field_conf = self.get_field(field.name)
- if not (getattr(self.Meta, 'fields_conf', {}).has_key(field.name) and self.Meta.fields_conf[field.name].has_key('editor')):
+ f = self.get_base_field(field.name)
+ # print dir(f)
+ #print 'base_field', f, f.widget
+ if field_conf and not (getattr(self.Meta, 'fields_conf', {}).has_key(field.name) and self.Meta.fields_conf[field.name].has_key('editor')):
field_conf['editor'] = forms.getFieldConfig(field.name, field)
+ #print 'getFieldConfig editor', field.name, field_conf['editor']
def update_instances_from_json(self, json, insert_new = True):
""" udpate this grid model instances from provided json
@@ -240,7 +260,7 @@ def update_instances_from_json(self, json, insert_new = True):
form_data = item_data.copy()
del form_data['id']
instance = self.model()
- #print pk, form_data
+ # print pk, form_data
if pk:
# get the related instance
instance = self.model.objects.get(pk = pk)
@@ -249,25 +269,20 @@ def update_instances_from_json(self, json, insert_new = True):
# skip if new and dont insert
continue
# get a ModelForm based on supplied fields
- #print 1
+ # todo : force mandatory fields !
+
form = forms.getExtJsModelForm(self.model, fields_list = form_data.keys())
- #print 2
form = form(form_data, instance = instance)
- #print 3
forms_items.append(form)
- #print 4
if not form.is_valid():
print 'invalid form', form.errors
errors.append(form.errors)
-
+
if not errors:
- for form in forms_items:
- # print 5
+ for form in forms_items:
form.save()
- # print 6
return True
else:
# todo : detailed errors
- # print 7
raise Exception(errors)
View
6 static/js/Ext.ux.AutoEditableGrid.js
@@ -117,6 +117,7 @@ Ext.ux.AutoEditableGrid = Ext.extend(Ext.ux.AutoGrid, {
,blinking:false
,task_blink:{
run: function(){
+ if (!this.btn_save) return;
nclass = (this.btn_save.counter%2==0)?'icon-disk-red':'icon-disk';
this.btn_save.setIconClass(nclass);
this.btn_save.counter+=1;
@@ -150,6 +151,11 @@ Ext.ux.AutoEditableGrid = Ext.extend(Ext.ux.AutoGrid, {
this.on('afteredit', function(e) {
this.btn_save.startBlink();
}, this);
+
+ this.on('beforedestroy', function(e) {
+ this.btn_save.stopBlink();
+ return true;
+ }, this);
}
});
Please sign in to comment.
Something went wrong with that request. Please try again.