-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathbase.py
More file actions
2760 lines (2223 loc) · 87.5 KB
/
base.py
File metadata and controls
2760 lines (2223 loc) · 87.5 KB
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
from __future__ import annotations
import csv
import inspect
import mimetypes
import re
import time
import typing as t
import warnings
from collections import OrderedDict
from math import ceil
from typing import cast
from flask import abort
from flask import current_app
from flask import flash
from flask import get_flashed_messages
from flask import json
from flask import redirect
from flask import request
from flask import stream_with_context
from jinja2 import pass_context
from jinja2.runtime import Context
from markupsafe import Markup
from werkzeug import Response
from werkzeug.utils import secure_filename
from .._types import T_COLUMN
from .._types import T_COLUMN_LIST
from .._types import T_COLUMN_TYPE_FORMATTERS
from .._types import T_FIELD_ARGS_VALIDATORS_FILES
from .._types import T_FILTER
from .._types import T_INSTRUMENTED_ATTRIBUTE
from .._types import T_ORM_MODEL
from .._types import T_PEEWEE_FIELD
from .._types import T_QUERY_AJAX_MODEL_LOADER
from .._types import T_RESPONSE
from .._types import T_RULES_SEQUENCE
from .._types import T_WIDGET
from ..form.rules import RuleSet
from .filters import BaseFilter
from .template import BaseListRowAction
try:
import tablib
except ImportError:
tablib = None
from typing import TypeGuard # noqa
from wtforms.fields import HiddenField
from wtforms.fields.core import Field
from wtforms.fields.core import UnboundField
from wtforms.form import Form
from wtforms.validators import InputRequired
from wtforms.validators import ValidationError
from flask_admin._backwards import ObsoleteAttr
from flask_admin._compat import as_unicode
from flask_admin._compat import csv_encode
from flask_admin._compat import iteritems
from flask_admin._compat import itervalues
from flask_admin._compat import text_type
from flask_admin.actions import ActionsMixin
from flask_admin.babel import gettext
from flask_admin.babel import ngettext
from flask_admin.base import BaseView
from flask_admin.base import expose
from flask_admin.form import BaseForm
from flask_admin.form import FormOpts
from flask_admin.form import rules
from flask_admin.helpers import flash_errors, is_form_submitted
from flask_admin.helpers import get_form_data
from flask_admin.helpers import get_redirect_target
from flask_admin.helpers import validate_form_on_submit
from flask_admin.model import filters
from flask_admin.model import template
from flask_admin.model import typefmt
from flask_admin.tools import rec_getattr
from .ajax import AjaxModelLoader
from .helpers import get_mdict_item_or_list
from .helpers import prettify_name
# Used to generate filter query string name
filter_char_re = re.compile("[^a-z0-9 ]")
filter_compact_re = re.compile(" +")
class ViewArgs:
"""
List view arguments.
"""
def __init__(
self,
page: int | None = None,
page_size: int | None = None,
sort: int | None = None,
sort_desc: int | None = None,
search: str | None = None,
filters: t.Sequence[T_FILTER] | None = None,
extra_args: dict[str, t.Any] | None = None,
) -> None:
self.page = page
self.page_size = page_size
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: t.Any) -> ViewArgs:
if self.filters:
flt = list(self.filters)
else:
flt = None
kwargs.setdefault("page", self.page)
kwargs.setdefault("page_size", self.page_size)
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 FilterGroup:
def __init__(self, label: str) -> None:
self.label = label
self.filters: list[dict[t.Any, t.Any]] = []
def append(self, filter: dict[t.Any, t.Any]) -> None:
self.filters.append(filter)
def non_lazy(self) -> tuple[str, list[dict[t.Any, t.Any]]]:
filters = []
for item in self.filters:
copy = dict(item)
copy["operation"] = as_unicode(copy["operation"])
options = copy["options"]
if options:
copy["options"] = [(k, text_type(v)) for k, v in options]
filters.append(copy)
return as_unicode(self.label), filters
def __iter__(self) -> t.Iterator[dict[t.Any, t.Any]]:
return iter(self.filters)
T_COLUMN_FORMATTERS = dict[
str,
t.Callable[
[
# First arg inherits from BaseModelView.
# Cannot type hint and allow users to override without type errors
t.Any,
Context | None,
t.Any,
str,
],
str | Markup,
],
]
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: bool = True
"""Is model creation allowed"""
can_edit: bool = True
"""Is model editing allowed"""
can_delete: bool = True
"""Is model deletion allowed"""
can_view_details: bool = False
"""
Setting this to true will enable the details view. This is recommended
when there are too many columns to display in the list_view.
"""
can_export: bool = False
"""Is model list export allowed"""
# Templates
list_template: str = "admin/model/list.html"
"""Default list view template"""
edit_template: str = "admin/model/edit.html"
"""Default edit template"""
create_template: str = "admin/model/create.html"
"""Default create template"""
details_template: str = "admin/model/details.html"
"""Default details view template"""
# Modal Templates
edit_modal_template: str = "admin/model/modals/edit.html"
"""Default edit modal template"""
create_modal_template: str = "admin/model/modals/create.html"
"""Default create modal template"""
details_modal_template: str = "admin/model/modals/details.html"
"""Default details modal view template"""
# Modals
edit_modal: bool = False
"""Setting this to true will display the edit_view as a modal dialog."""
create_modal: bool = False
"""Setting this to true will display the create_view as a modal dialog."""
details_modal: bool = False
"""Setting this to true will display the details_view as a modal dialog."""
# Customizations
column_list: T_COLUMN_LIST | None = cast(
None, 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')
(Added in 1.4.0) SQLAlchemy model attributes can be used instead of strings::
class MyModelView(BaseModelView):
column_list = ('name', User.last_name)
When using SQLAlchemy models, you can reference related columns like this::
class MyModelView(BaseModelView):
column_list = ('<relationship>.<related column name>',)
"""
column_exclude_list: t.Sequence[str] | None = cast(
None, 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_details_list: list[str] | None = None
"""
Collection of the field names included in the details view.
If set to `None`, will get them from the model.
"""
column_details_exclude_list: list[str] | None = None
"""
Collection of fields excluded from the details view.
"""
column_export_list: list[str] | None = None
"""
Collection of the field names included in the export.
If set to `None`, will get them from the model.
"""
column_export_exclude_list: list[str] | None = None
"""
Collection of fields excluded from the export.
"""
column_formatters: T_COLUMN_FORMATTERS = cast(
T_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_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_formatters_export: T_COLUMN_FORMATTERS | None = None
"""
Dictionary of list view column formatters to be used for export.
Defaults to column_formatters when set to None.
Functions the same way as column_formatters except
that macros are not supported.
"""
column_formatters_detail: T_COLUMN_FORMATTERS | None = None
"""
Dictionary of list view column formatters to be used for the detail view.
Defaults to column_formatters when set to None.
Functions the same way as column_formatters except
that macros are not supported.
that macros are not supported.
"""
column_type_formatters: T_COLUMN_TYPE_FORMATTERS | None = cast(
None, ObsoleteAttr("column_type_formatters", "list_type_formatters", None)
)
"""
Dictionary of value type formatters to be used in the list view.
By default, three types are formatted:
1. ``None`` will be displayed as an empty string
2. ``bool`` will be displayed as a checkmark if it is ``True``
3. ``list`` will be joined using ', '
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. Also comes with bonus `date` formatter::
from datetime import date
from flask_admin.model import typefmt
def date_format(view, value):
return value.strftime('%d.%m.%Y')
MY_DEFAULT_FORMATTERS = dict(typefmt.BASE_FORMATTERS)
MY_DEFAULT_FORMATTERS.update({
type(None): typefmt.null_formatter,
date: date_format
})
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, name) -> str:
# `view` is current administrative view
# `value` value to format
# `field` is name of field
return "Value to display"
For backward compatibility, the callback function can also omit
the 'name' param, but a warning will be raised.
"""
column_type_formatters_export: T_COLUMN_TYPE_FORMATTERS | None = None
"""
Dictionary of value type formatters to be used in the export.
By default, two types are formatted:
1. ``None`` will be displayed as an empty string
2. ``list`` will be joined using ', '
Functions the same way as column_type_formatters.
"""
column_type_formatters_detail: T_COLUMN_TYPE_FORMATTERS | None = None
"""
Dictionary of value type formatters to be used in the detail view.
By default, two types are formatted:
1. ``None`` will be displayed as an empty string
2. ``list`` will be joined using ', '
Functions the same way as column_type_formatters.
"""
column_labels: dict[str, str] = cast(
dict[str, str], 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: dict[str, str] | None = 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: T_COLUMN_LIST | None = cast(
None,
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'))
You can also specify multiple fields to be used while sorting::
class MyModelView(BaseModelView):
column_sortable_list = (
'name', ('user', ('user.first_name', 'user.last_name')))
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 | str | tuple[str, bool] | list[tuple[str, bool]] = 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)
If you want to sort by more than one column,
you can pass a list of tuples::
class MyModelView(BaseModelView):
column_default_sort = [('name', True), ('last_name', True)]
"""
column_searchable_list: T_COLUMN_LIST | None = cast(
None,
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: t.Collection[str] | None = 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: dict[str, t.Sequence[tuple[str, str]]] | None = None
"""
Map choices to columns in list view
Example::
class MyModelView(BaseModelView):
column_choices = {
'my_column': [
('db_value', 'display_value'),
]
}
"""
column_filters: t.Collection[str | BaseFilter] | None = None
"""
Collection of the column filters.
Can contain either field names or instances of
:class:`~flask_admin.model.filters.BaseFilter` classes.
Example::
class MyModelView(BaseModelView):
column_filters = ('user', 'email')
"""
named_filter_urls: bool = 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: bool = cast(
bool, ObsoleteAttr("column_display_pk", "list_display_pk", False)
)
"""
Controls if the primary key should be displayed in the list view.
"""
column_display_actions: bool = True
"""
Controls the display of the row actions (edit, delete, details, etc.)
column in the list view.
Useful for preventing a blank column from displaying if your view does
not use any build-in or custom row actions.
This column is not hidden automatically due to backwards compatibility.
Note: This only affects display and does not control whether the row
actions endpoints are accessible.
"""
column_extra_row_actions: list[BaseListRowAction] | None = None
"""
List of row actions
(instances of :class:`~flask_admin.model.template.BaseListRowAction`).
Flask-Admin will generate standard per-row actions (edit, delete, etc)
and will append custom actions from this list right after them.
For example::
from flask_admin.model.template import EndpointLinkRowAction, LinkRowAction
class MyModelView(BaseModelView):
column_extra_row_actions = [
LinkRowAction(
'bi bi-rocket-takeoff', 'http://direct.link/?id={row_id}'
),
EndpointLinkRowAction(
'bi bi-box-arrow-up-right', 'my_view.index_view'
)
]
"""
simple_list_pager: bool = False
"""
Enable or disable simple list pager.
If enabled, model interface would not run count query and will only show
prev/next pager buttons.
"""
form: type[Form] | None = 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: type[BaseForm] = BaseForm
"""
Base form class. Will be used by form scaffolding function when creating model
form.
Useful if you want to have custom constructor or override some fields.
Example::
class MyBaseForm(Form):
def do_something(self):
pass
class MyModelView(BaseModelView):
form_base_class = MyBaseForm
"""
form_args: dict[str, T_FIELD_ARGS_VALIDATORS_FILES] | None = None
"""
Dictionary of form field arguments. Refer to WTForms documentation for
list of possible options.
Example::
from wtforms.validators import DataRequired
class MyModelView(BaseModelView):
form_args = dict(
name=dict(label='First Name', validators=[DataRequired()])
)
"""
form_columns: t.Collection[t.Union[str, T_INSTRUMENTED_ATTRIBUTE]] | None = 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')
(Added in 1.4.0) SQLAlchemy model attributes can be used instead of
strings::
class MyModelView(BaseModelView):
form_columns = ('name', User.last_name)
SQLA Note: Model attributes must be on the same model as your ModelView
or you will need to use `inline_models`.
"""
form_excluded_columns: t.Collection[str] = cast(
t.Collection[str],
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: dict[str, type[Field]] | None = None
"""
Dictionary of form column overrides.
Example::
class MyModelView(BaseModelView):
form_overrides = dict(name=wtf.FileField)
"""
form_widget_args: dict[str, dict[str, int | str | bool]] | None = 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'
},
'other_field': {
'disabled': True
}
}
Changing the format of a DateTimeField will require changes to both
form_widget_args and form_args.
Example::
form_args = dict(
# changes how the input is parsed by strptime (12 hour time)
start=dict(format='%Y-%m-%d %I:%M %p')
)
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: dict[str, Field] | None = 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: (
dict[
str,
AjaxModelLoader
| dict[
str | T_COLUMN, str | t.Iterable[str | T_PEEWEE_FIELD | T_COLUMN] | int
],
]
| None
) = 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'),
'placeholder': 'Please select',
'page_size': 10,
'minimum_input_length': 0,
}
}
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: T_RULES_SEQUENCE | None = 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_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: T_RULES_SEQUENCE | None = None
"""
Customized rules for the edit form. Override `form_rules` if present.
"""
form_create_rules: T_RULES_SEQUENCE | None = None
"""
Customized rules for the create form. Override `form_rules` if present.
"""
# Actions
action_disallowed_list: t.Sequence[str] = cast(
t.Sequence[str],
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']
"""
# Export settings
export_max_rows: int = 0
"""
Maximum number of rows allowed for export.
Unlimited by default. Uses `page_size` if set to `None`.
"""
export_types: t.Collection[str] = ["csv"]
"""
A list of available export filetypes. `csv` only is default, but any
filetypes supported by tablib can be used.
Check tablib for https://tablib.readthedocs.io/en/stable/formats.html
for supported types.
"""
# Pagination settings
page_size: int = 20
"""
Default page size for pagination.
"""
can_set_page_size: bool = False
"""
Allows to select page size via dropdown list
"""
page_size_options: tuple[int, ...] = (20, 50, 100)
"""
Sets the page size options available, if `can_set_page_size` is True
"""
def __init__(
self,
model: type[T_ORM_MODEL],
name: str | None = None,
category: str | None = None,
endpoint: str | None = None,
url: str | None = None,
static_folder: str | None = None,
menu_class_name: str | None = None,
menu_icon_type: str | None = None,
menu_icon_value: str | None = None,
) -> None:
"""
Constructor.
:param model:
Model class type
:param name:
View name. If not provided, will use the model class name
:param category:
Optional category name, for grouping views in the menu
:param endpoint:
Base endpoint. If not provided, will use the model name.
: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_admin.consts.ICON_TYPE_BOOTSTRAP` - Bootstrap icon
- `flask_admin.consts.ICON_TYPE_FONT_AWESOME` - Font Awesome icon
- `flask_admin.consts.ICON_TYPE_IMAGE` - Image relative to Flask
static directory
- `flask_admin.consts.ICON_TYPE_IMAGE_URL` - Image with full URL
:param menu_icon_value:
Icon name (Fontawesome, or Bootstrap) or URL, depending on
`menu_icon_type` setting
"""
self.model = model
# If name not provided, it is model name
if name is None:
name = f"{self._prettify_class_name(model.__name__)}"
super().__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()
if self.can_set_page_size and self.page_size not in self.page_size_options:
warnings.warn(
f"{self.page_size=} is not in {self.page_size_options=}",
UserWarning,
stacklevel=1,
)
# Endpoint
def _get_endpoint(self, endpoint: str | None) -> str:
if endpoint:
return super()._get_endpoint(endpoint)
return self.model.__name__.lower()
# Caching
def _refresh_forms_cache(self) -> None:
# Forms
self._form_ajax_refs: dict[str, AjaxModelLoader | T_QUERY_AJAX_MODEL_LOADER] = (
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()
self._action_form_class = self.get_action_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) -> None: