-
Notifications
You must be signed in to change notification settings - Fork 81
/
base.py
1633 lines (1265 loc) · 50.7 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import warnings
import re
from flask import (request, redirect, flash, abort, json, Response,
get_flashed_messages)
from jinja2 import contextfunction
from wtforms.fields import HiddenField
from wtforms.validators import ValidationError, Required
from flask.ext.admin.babel import gettext
from flask.ext.admin.base import BaseView, expose
from flask.ext.admin.form import BaseForm, FormOpts, rules
from flask.ext.admin.model import filters, typefmt
from flask.ext.admin.actions import ActionsMixin
from flask.ext.admin.helpers import (get_form_data, validate_form_on_submit,
get_redirect_target, flash_errors)
from flask.ext.admin.tools import rec_getattr
from flask.ext.admin._backwards import ObsoleteAttr
from flask.ext.admin._compat import iteritems, OrderedDict, as_unicode
from .helpers import prettify_name, get_mdict_item_or_list
from .ajax import AjaxModelLoader
from .fields import ListEditableFieldList
# Used to generate filter query string name
filter_char_re = re.compile('[^a-z0-9 ]')
filter_compact_re = re.compile(' +')
class ViewArgs(object):
"""
List view arguments.
"""
def __init__(self, page=None, sort=None, sort_desc=None, search=None, filters=None, extra_args=None):
self.page = page
self.sort = sort
self.sort_desc = bool(sort_desc)
self.search = search
self.filters = filters
if not self.search:
self.search = None
self.extra_args = extra_args or dict()
def clone(self, **kwargs):
if self.filters:
flt = list(self.filters)
else:
flt = None
kwargs.setdefault('page', self.page)
kwargs.setdefault('sort', self.sort)
kwargs.setdefault('sort_desc', self.sort_desc)
kwargs.setdefault('search', self.search)
kwargs.setdefault('filters', flt)
kwargs.setdefault('extra_args', dict(self.extra_args))
return ViewArgs(**kwargs)
class BaseModelView(BaseView, ActionsMixin):
"""
Base model view.
This view does not make any assumptions on how models are stored or managed, but expects the following:
1. The provided model is an object
2. The model contains properties
3. Each model contains an attribute which uniquely identifies it (i.e. a primary key for a database model)
4. It is possible to retrieve a list of sorted models with pagination applied from a data source
5. You can get one model by its identifier from the data source
Essentially, if you want to support a new data store, all you have to do is:
1. Derive from the `BaseModelView` class
2. Implement various data-related methods (`get_list`, `get_one`, `create_model`, etc)
3. Implement automatic form generation from the model representation (`scaffold_form`)
"""
# Permissions
can_create = True
"""Is model creation allowed"""
can_edit = True
"""Is model editing allowed"""
can_delete = True
"""Is model deletion allowed"""
# Templates
list_template = 'admin/model/list.html'
"""Default list view template"""
edit_template = 'admin/model/edit.html'
"""Default edit template"""
create_template = 'admin/model/create.html'
"""Default create template"""
# Customizations
column_list = ObsoleteAttr('column_list', 'list_columns', None)
"""
Collection of the model field names for the list view.
If set to `None`, will get them from the model.
For example::
class MyModelView(BaseModelView):
column_list = ('name', 'last_name', 'email')
"""
column_exclude_list = ObsoleteAttr('column_exclude_list',
'excluded_list_columns', None)
"""
Collection of excluded list column names.
For example::
class MyModelView(BaseModelView):
column_exclude_list = ('last_name', 'email')
"""
column_formatters = ObsoleteAttr('column_formatters', 'list_formatters', dict())
"""
Dictionary of list view column formatters.
For example, if you want to show price multiplied by
two, you can do something like this::
class MyModelView(BaseModelView):
column_formatters = dict(price=lambda v, c, m, p: m.price*2)
or using Jinja2 `macro` in template::
from flask.ext.admin.model.template import macro
class MyModelView(BaseModelView):
column_formatters = dict(price=macro('render_price'))
# in template
{% macro render_price(model, column) %}
{{ model.price * 2 }}
{% endmacro %}
The Callback function has the prototype::
def formatter(view, context, model, name):
# `view` is current administrative view
# `context` is instance of jinja2.runtime.Context
# `model` is model instance
# `name` is property name
pass
"""
column_type_formatters = ObsoleteAttr('column_type_formatters', 'list_type_formatters', None)
"""
Dictionary of value type formatters to be used in the list view.
By default, two types are formatted:
1. ``None`` will be displayed as an empty string
2. ``bool`` will be displayed as a checkmark if it is ``True``
If you don't like the default behavior and don't want any type formatters
applied, just override this property with an empty dictionary::
class MyModelView(BaseModelView):
column_type_formatters = dict()
If you want to display `NULL` instead of an empty string, you can do
something like this::
from flask.ext.admin.model import typefmt
MY_DEFAULT_FORMATTERS = dict(typefmt.BASE_FORMATTERS)
MY_DEFAULT_FORMATTERS.update({
type(None): typefmt.null_formatter
})
class MyModelView(BaseModelView):
column_type_formatters = MY_DEFAULT_FORMATTERS
Type formatters have lower priority than list column formatters.
The callback function has following prototype::
def type_formatter(view, value):
# `view` is current administrative view
# `value` value to format
pass
"""
column_labels = ObsoleteAttr('column_labels', 'rename_columns', None)
"""
Dictionary where key is column name and value is string to display.
For example::
class MyModelView(BaseModelView):
column_labels = dict(name='Name', last_name='Last Name')
"""
column_descriptions = None
"""
Dictionary where key is column name and
value is description for `list view` column or add/edit form field.
For example::
class MyModelView(BaseModelView):
column_descriptions = dict(
full_name='First and Last name'
)
"""
column_sortable_list = ObsoleteAttr('column_sortable_list',
'sortable_columns',
None)
"""
Collection of the sortable columns for the list view.
If set to `None`, will get them from the model.
For example::
class MyModelView(BaseModelView):
column_sortable_list = ('name', 'last_name')
If you want to explicitly specify field/column to be used while
sorting, you can use a tuple::
class MyModelView(BaseModelView):
column_sortable_list = ('name', ('user', 'user.username'))
When using SQLAlchemy models, model attributes can be used instead
of strings::
class MyModelView(BaseModelView):
column_sortable_list = ('name', ('user', User.username))
"""
column_default_sort = None
"""
Default sort column if no sorting is applied.
Example::
class MyModelView(BaseModelView):
column_default_sort = 'user'
You can use tuple to control ascending descending order. In following example, items
will be sorted in descending order::
class MyModelView(BaseModelView):
column_default_sort = ('user', True)
"""
column_searchable_list = ObsoleteAttr('column_searchable_list',
'searchable_columns',
None)
"""
A collection of the searchable columns. It is assumed that only
text-only fields are searchable, but it is up to the model
implementation to decide.
Example::
class MyModelView(BaseModelView):
column_searchable_list = ('name', 'email')
"""
column_editable_list = None
"""
Collection of the columns which can be edited from the list view.
For example::
class MyModelView(BaseModelView):
column_editable_list = ('name', 'last_name')
"""
column_choices = None
"""
Map choices to columns in list view
Example::
class MyModelView(BaseModelView):
column_choices = {
'my_column': [
('db_value', 'display_value'),
]
}
"""
column_filters = None
"""
Collection of the column filters.
Can contain either field names or instances of :class:`~flask.ext.admin.model.filters.BaseFilter` classes.
Example::
class MyModelView(BaseModelView):
column_filters = ('user', 'email')
"""
named_filter_urls = False
"""
Set to True to use human-readable names for filters in URL parameters.
False by default so as to be robust across translations.
Changing this parameter will break any existing URLs that have filters.
"""
column_display_pk = ObsoleteAttr('column_display_pk',
'list_display_pk',
False)
"""
Controls if the primary key should be displayed in the list view.
"""
form = None
"""
Form class. Override if you want to use custom form for your model.
Will completely disable form scaffolding functionality.
For example::
class MyForm(Form):
name = StringField('Name')
class MyModelView(BaseModelView):
form = MyForm
"""
form_base_class = BaseForm
"""
Base form class. Will be used by form scaffolding function when creating model form.
Useful if you want to have custom contructor or override some fields.
Example::
class MyBaseForm(Form):
def do_something(self):
pass
class MyModelView(BaseModelView):
form_base_class = MyBaseForm
"""
form_args = None
"""
Dictionary of form field arguments. Refer to WTForms documentation for
list of possible options.
Example::
from wtforms.validators import required
class MyModelView(BaseModelView):
form_args = dict(
name=dict(label='First Name', validators=[required()])
)
"""
form_columns = None
"""
Collection of the model field names for the form. If set to `None` will
get them from the model.
Example::
class MyModelView(BaseModelView):
form_columns = ('name', 'email')
"""
form_excluded_columns = ObsoleteAttr('form_excluded_columns',
'excluded_form_columns',
None)
"""
Collection of excluded form field names.
For example::
class MyModelView(BaseModelView):
form_excluded_columns = ('last_name', 'email')
"""
form_overrides = None
"""
Dictionary of form column overrides.
Example::
class MyModelView(BaseModelView):
form_overrides = dict(name=wtf.FileField)
"""
form_widget_args = None
"""
Dictionary of form widget rendering arguments.
Use this to customize how widget is rendered without using custom template.
Example::
class MyModelView(BaseModelView):
form_widget_args = {
'description': {
'rows': 10,
'style': 'color: black'
}
}
Changing the format of a DateTimeField will require changes to both form_widget_args and form_args.
Example::
form_args = dict(
start=dict(format='%Y-%m-%d %I:%M %p') # changes how the input is parsed by strptime (12 hour time)
)
form_widget_args = dict(
start={'data-date-format': u'yyyy-mm-dd HH:ii P', 'data-show-meridian': 'True'} # changes how the DateTimeField displays the time
)
"""
form_extra_fields = None
"""
Dictionary of additional fields.
Example::
class MyModelView(BaseModelView):
form_extra_fields = {
password: PasswordField('Password')
}
You can control order of form fields using ``form_columns`` property. For example::
class MyModelView(BaseModelView):
form_columns = ('name', 'email', 'password', 'secret')
form_extra_fields = {
password: PasswordField('Password')
}
In this case, password field will be put between email and secret fields that are autogenerated.
"""
form_ajax_refs = None
"""
Use AJAX for foreign key model loading.
Should contain dictionary, where key is field name and value is either a dictionary which
configures AJAX lookups or backend-specific `AjaxModelLoader` class instance.
For example, it can look like::
class MyModelView(BaseModelView):
form_ajax_refs = {
'user': {
'fields': ('first_name', 'last_name', 'email')
'page_size': 10
}
}
Or with SQLAlchemy backend like this::
class MyModelView(BaseModelView):
form_ajax_refs = {
'user': QueryAjaxModelLoader('user', db.session, User, fields=['email'], page_size=10)
}
If you need custom loading functionality, you can implement your custom loading behavior
in your `AjaxModelLoader` class.
"""
form_rules = None
"""
List of rendering rules for model creation form.
This property changed default form rendering behavior and makes possible to rearrange order
of rendered fields, add some text between fields, group them, etc. If not set, will use
default Flask-Admin form rendering logic.
Here's simple example which illustrates how to use::
from flask.ext.admin.form import rules
class MyModelView(ModelView):
form_rules = [
# Define field set with header text and four fields
rules.FieldSet(('first_name', 'last_name', 'email', 'phone'), 'User'),
# ... and it is just shortcut for:
rules.Header('User'),
rules.Field('first_name'),
rules.Field('last_name'),
# ...
# It is possible to create custom rule blocks:
MyBlock('Hello World'),
# It is possible to call macros from current context
rules.Macro('my_macro', foobar='baz')
]
"""
form_edit_rules = None
"""
Customized rules for the edit form. Override `form_rules` if present.
"""
form_create_rules = None
"""
Customized rules for the create form. Override `form_rules` if present.
"""
# Actions
action_disallowed_list = ObsoleteAttr('action_disallowed_list',
'disallowed_actions',
[])
"""
Set of disallowed action names. For example, if you want to disable
mass model deletion, do something like this:
class MyModelView(BaseModelView):
action_disallowed_list = ['delete']
"""
# Various settings
page_size = 20
"""
Default page size for pagination.
"""
def __init__(self, model,
name=None, category=None, endpoint=None, url=None, static_folder=None,
menu_class_name=None, menu_icon_type=None, menu_icon_value=None):
"""
Constructor.
:param model:
Model class
:param name:
View name. If not provided, will use the model class name
:param category:
View category
:param endpoint:
Base endpoint. If not provided, will use the model name + 'view'.
For example if model name was 'User', endpoint will be
'userview'
:param url:
Base URL. If not provided, will use endpoint as a URL.
:param menu_class_name:
Optional class name for the menu item.
:param menu_icon_type:
Optional icon. Possible icon types:
- `flask.ext.admin.consts.ICON_TYPE_GLYPH` - Bootstrap glyph icon
- `flask.ext.admin.consts.ICON_TYPE_IMAGE` - Image relative to Flask static directory
- `flask.ext.admin.consts.ICON_TYPE_IMAGE_URL` - Image with full URL
:param menu_icon_value:
Icon glyph name or URL, depending on `menu_icon_type` setting
"""
self.model = model
# If name not provided, it is model name
if name is None:
name = '%s' % self._prettify_class_name(model.__name__)
super(BaseModelView, self).__init__(name, category, endpoint, url, static_folder,
menu_class_name=menu_class_name,
menu_icon_type=menu_icon_type,
menu_icon_value=menu_icon_value)
# Actions
self.init_actions()
# Scaffolding
self._refresh_cache()
# Endpoint
def _get_endpoint(self, endpoint):
if endpoint:
return super(BaseModelView, self)._get_endpoint(endpoint)
return self.__class__.__name__.lower()
# Caching
def _refresh_forms_cache(self):
# Forms
self._form_ajax_refs = self._process_ajax_references()
if self.form_widget_args is None:
self.form_widget_args = {}
self._create_form_class = self.get_create_form()
self._edit_form_class = self.get_edit_form()
self._delete_form_class = self.get_delete_form()
# List View In-Line Editing
if self.column_editable_list:
self._list_form_class = self.get_list_form()
else:
self.column_editable_list = {}
def _refresh_filters_cache(self):
self._filters = self.get_filters()
if self._filters:
self._filter_groups = OrderedDict()
self._filter_args = {}
for i, flt in enumerate(self._filters):
if flt.name not in self._filter_groups:
self._filter_groups[flt.name] = []
self._filter_groups[flt.name].append({
'index': i,
'arg': self.get_filter_arg(i, flt),
'operation': as_unicode(flt.operation()),
'options': flt.get_options(self) or None,
'type': flt.data_type
})
self._filter_args[self.get_filter_arg(i, flt)] = (i, flt)
else:
self._filter_groups = None
self._filter_args = None
def _refresh_form_rules_cache(self):
if self.form_create_rules:
self._form_create_rules = rules.RuleSet(self, self.form_create_rules)
else:
self._form_create_rules = None
if self.form_edit_rules:
self._form_edit_rules = rules.RuleSet(self, self.form_edit_rules)
else:
self._form_edit_rules = None
if self.form_rules:
form_rules = rules.RuleSet(self, self.form_rules)
if not self._form_create_rules:
self._form_create_rules = form_rules
if not self._form_edit_rules:
self._form_edit_rules = form_rules
def _refresh_cache(self):
"""
Refresh various cached variables.
"""
# List view
self._list_columns = self.get_list_columns()
self._sortable_columns = self.get_sortable_columns()
# Labels
if self.column_labels is None:
self.column_labels = {}
# Forms
self._refresh_forms_cache()
# Search
self._search_supported = self.init_search()
# Choices
if self.column_choices:
self._column_choices_map = dict([
(column, dict(choices))
for column, choices in self.column_choices.items()
])
else:
self.column_choices = self._column_choices_map = dict()
# Type formatters
if self.column_type_formatters is None:
self.column_type_formatters = dict(typefmt.BASE_FORMATTERS)
if self.column_descriptions is None:
self.column_descriptions = dict()
# Filters
self._refresh_filters_cache()
# Form rendering rules
self._refresh_form_rules_cache()
# Primary key
def get_pk_value(self, model):
"""
Return PK value from a model object.
"""
raise NotImplementedError()
# List view
def scaffold_list_columns(self):
"""
Return list of the model field names. Must be implemented in
the child class.
Expected return format is list of tuples with field name and
display text. For example::
['name', 'first_name', 'last_name']
"""
raise NotImplementedError('Please implement scaffold_list_columns method')
def get_column_name(self, field):
"""
Return a human-readable column name.
:param field:
Model field name.
"""
if self.column_labels and field in self.column_labels:
return self.column_labels[field]
else:
return self._prettify_name(field)
def get_list_columns(self):
"""
Returns a list of the model field names. If `column_list` was
set, returns it. Otherwise calls `scaffold_list_columns`
to generate the list from the model.
"""
columns = self.column_list
if columns is None:
columns = self.scaffold_list_columns()
# Filter excluded columns
if self.column_exclude_list:
columns = [c for c in columns if c not in self.column_exclude_list]
return [(c, self.get_column_name(c)) for c in columns]
def scaffold_sortable_columns(self):
"""
Returns dictionary of sortable columns. Must be implemented in
the child class.
Expected return format is a dictionary, where keys are field names and
values are property names.
"""
raise NotImplementedError('Please implement scaffold_sortable_columns method')
def get_sortable_columns(self):
"""
Returns a dictionary of the sortable columns. Key is a model
field name and value is sort column (for example - attribute).
If `column_sortable_list` is set, will use it. Otherwise, will call
`scaffold_sortable_columns` to get them from the model.
"""
if self.column_sortable_list is None:
return self.scaffold_sortable_columns() or dict()
else:
result = dict()
for c in self.column_sortable_list:
if isinstance(c, tuple):
result[c[0]] = c[1]
else:
result[c] = c
return result
def init_search(self):
"""
Initialize search. If data provider does not support search,
`init_search` will return `False`.
"""
return False
# Filter helpers
def scaffold_filters(self, name):
"""
Generate filter object for the given name
:param name:
Name of the field
"""
return None
def is_valid_filter(self, filter):
"""
Verify that the provided filter object is valid.
Override in model backend implementation to verify if
the provided filter type is allowed.
:param filter:
Filter object to verify.
"""
return isinstance(filter, filters.BaseFilter)
def handle_filter(self, filter):
"""
Postprocess (add joins, etc) for a filter.
:param filter:
Filter object to postprocess
"""
return filter
def get_filters(self):
"""
Return a list of filter objects.
If your model backend implementation does not support filters,
override this method and return `None`.
"""
if self.column_filters:
collection = []
for n in self.column_filters:
if self.is_valid_filter(n):
collection.append(self.handle_filter(n))
else:
flt = self.scaffold_filters(n)
if flt:
collection.extend(flt)
else:
raise Exception('Unsupported filter type %s' % n)
return collection
else:
return None
def get_filter_arg(self, index, flt):
"""
Given a filter `flt`, return a unique name for that filter in
this view.
Does not include the `flt[n]_` portion of the filter name.
:param index:
Filter index in _filters array
:param flt:
Filter instance
"""
if self.named_filter_urls:
name = ('%s %s' % (flt.name, as_unicode(flt.operation()))).lower()
name = filter_char_re.sub('', name)
name = filter_compact_re.sub('_', name)
return name
else:
return str(index)
# Form helpers
def scaffold_form(self):
"""
Create `form.BaseForm` inherited class from the model. Must be
implemented in the child class.
"""
raise NotImplementedError('Please implement scaffold_form method')
def scaffold_list_form(self, custom_fieldlist=ListEditableFieldList,
validators=None):
"""
Create form for the `index_view` using only the columns from
`self.column_editable_list`.
:param validators:
`form_args` dict with only validators
{'name': {'validators': [required()]}}
:param custom_fieldlist:
A WTForm FieldList class. By default, `ListEditableFieldList`.
Must be implemented in the child class.
"""
raise NotImplementedError('Please implement scaffold_list_form method')
def get_form(self):
"""
Get form class.
If ``self.form`` is set, will return it and will call
``self.scaffold_form`` otherwise.
Override to implement customized behavior.
"""
if self.form is not None:
return self.form
return self.scaffold_form()
def get_list_form(self):
"""
Get form class for the editable list view.
Uses only validators from `form_args` to build the form class.
Allows overriding the editable list view field/widget. For example::
from flask.ext.admin.model.fields import ListEditableFieldList
from flask.ext.admin.model.widgets import XEditableWidget
class CustomWidget(XEditableWidget):
def get_kwargs(self, subfield, kwargs):
if subfield.type == 'TextAreaField':
kwargs['data-type'] = 'textarea'
kwargs['data-rows'] = '20'
# elif: kwargs for other fields
return kwargs
class CustomFieldList(ListEditableFieldList):
widget = CustomWidget()
class MyModelView(BaseModelView):
def get_list_form(self):
return self.scaffold_list_form(CustomFieldList)
"""
if self.form_args:
# get only validators, other form_args can break FieldList wrapper
validators = dict(
(key, {'validators': value["validators"]})
for key, value in iteritems(self.form_args)
if value.get("validators")
)
else:
validators = None
return self.scaffold_list_form(validators=validators)
def get_create_form(self):
"""
Create form class for model creation view.
Override to implement customized behavior.
"""
return self.get_form()
def get_edit_form(self):
"""
Create form class for model editing view.
Override to implement customized behavior.
"""
return self.get_form()
def get_delete_form(self):
"""
Create form class for model delete view.
Override to implement customized behavior.
"""
class DeleteForm(self.form_base_class):
id = HiddenField(validators=[Required()])
url = HiddenField()
return DeleteForm
def create_form(self, obj=None):
"""
Instantiate model creation form and return it.
Override to implement custom behavior.
"""
return self._create_form_class(get_form_data(), obj=obj)
def edit_form(self, obj=None):
"""
Instantiate model editing form and return it.
Override to implement custom behavior.
"""
return self._edit_form_class(get_form_data(), obj=obj)
def delete_form(self):
"""
Instantiate model delete form and return it.
Override to implement custom behavior.
The delete form originally used a GET request, so delete_form
accepts both GET and POST request for backwards compatibility.
"""
if request.form:
return self._delete_form_class(request.form)
elif request.args:
# allow request.args for backward compatibility
return self._delete_form_class(request.args)
else:
return self._delete_form_class()
def list_form(self, obj=None):
"""
Instantiate model editing form for list view and return it.
Override to implement custom behavior.
"""
return self._list_form_class(get_form_data(), obj=obj)
def validate_form(self, form):
"""
Validate the form on submit.