forked from dpgaspar/Flask-AppBuilder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbaseviews.py
1413 lines (1236 loc) · 47 KB
/
baseviews.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
from datetime import date, datetime
from inspect import isclass
import json
import logging
import re
from flask import (
abort,
Blueprint,
current_app,
flash,
render_template,
request,
session,
url_for,
)
from ._compat import as_unicode
from .actions import ActionItem
from .const import PERMISSION_PREFIX
from .forms import GeneralModelConverter
from .hooks import get_before_request_hooks, wrap_route_handler_with_hooks
from .urltools import (
get_filter_args,
get_order_args,
get_page_args,
get_page_size_args,
Stack,
)
from .widgets import FormWidget, ListWidget, SearchWidget, ShowWidget
log = logging.getLogger(__name__)
def expose(url="/", methods=("GET",)):
"""
Use this decorator to expose views on your view classes.
:param url:
Relative URL for the view
:param methods:
Allowed HTTP methods. By default only GET is allowed.
"""
def wrap(f):
if not hasattr(f, "_urls"):
f._urls = []
f._urls.append((url, methods))
return f
return wrap
def expose_api(name="", url="", methods=("GET",), description=""):
def wrap(f):
api_name = name or f.__name__
api_url = url or "/api/{0}".format(name)
if not hasattr(f, "_urls"):
f._urls = []
f._extra = {}
f._urls.append((api_url, methods))
f._extra[api_name] = (api_url, f.__name__, description)
return f
return wrap
class BaseView(object):
"""
All views inherit from this class.
it's constructor will register your exposed urls on flask as a Blueprint.
This class does not expose any urls, but provides a common base for all views.
Extend this class if you want to expose methods for your own templates
"""
appbuilder = None
blueprint = None
endpoint = None
route_base = None
""" Override this if you want to define your own relative url """
template_folder = "templates"
""" The template folder relative location """
static_folder = "static"
""" The static folder relative location """
base_permissions = None
"""
List with allowed base permission.
Use it like this if you want to restrict your view to readonly::
class MyView(ModelView):
base_permissions = ['can_list','can_show']
"""
class_permission_name = None
"""
Override class permission name default fallback to self.__class__.__name__
"""
previous_class_permission_name = None
"""
If set security cleanup will remove all permissions tuples
with this name
"""
method_permission_name = None
"""
Override method permission names, example::
method_permissions_name = {
'get_list': 'read',
'get': 'read',
'put': 'write',
'post': 'write',
'delete': 'write'
}
"""
previous_method_permission_name = None
"""
Use same structure as method_permission_name. If set security converge
will replace all method permissions by the new ones
"""
exclude_route_methods = set()
"""
Does not register routes for a set of builtin ModelView functions.
example::
class ContactModelView(ModelView):
datamodel = SQLAInterface(Contact)
exclude_route_methods = {"delete", "edit"}
"""
include_route_methods = None
"""
If defined will assume a white list setup, where all endpoints are excluded
except those define on this attribute
example::
class ContactModelView(ModelView):
datamodel = SQLAInterface(Contact)
include_route_methods = {"list"}
The previous example will exclude all endpoints except the `list` endpoint
"""
default_view = "list"
""" the default view for this BaseView, to be used with url_for (method name) """
extra_args = None
""" dictionary for injecting extra arguments into template """
_apis = None
def __init__(self):
"""
Initialization of base permissions
based on exposed methods and actions
Initialization of extra args
"""
# Init class permission override attrs
if not self.previous_class_permission_name and self.class_permission_name:
self.previous_class_permission_name = self.__class__.__name__
self.class_permission_name = (
self.class_permission_name or self.__class__.__name__
)
# Init previous permission override attrs
is_collect_previous = False
if not self.previous_method_permission_name and self.method_permission_name:
self.previous_method_permission_name = dict()
is_collect_previous = True
self.method_permission_name = self.method_permission_name or dict()
# Collect base_permissions and infer previous permissions
is_add_base_permissions = False
if self.base_permissions is None:
self.base_permissions = set()
is_add_base_permissions = True
for attr_name in dir(self):
# If include_route_methods is not None white list
if (
self.include_route_methods is not None
and attr_name not in self.include_route_methods
):
continue
# Don't create permission for excluded routes
if attr_name in self.exclude_route_methods:
continue
if hasattr(getattr(self, attr_name), "_permission_name"):
if is_collect_previous:
self.previous_method_permission_name[attr_name] = getattr(
getattr(self, attr_name), "_permission_name"
)
_permission_name = self.get_method_permission(attr_name)
if is_add_base_permissions:
self.base_permissions.add(PERMISSION_PREFIX + _permission_name)
self.base_permissions = list(self.base_permissions)
if not self.extra_args:
self.extra_args = dict()
self._apis = dict()
for attr_name in dir(self):
if hasattr(getattr(self, attr_name), "_extra"):
_extra = getattr(getattr(self, attr_name), "_extra")
for key in _extra:
self._apis[key] = _extra[key]
def create_blueprint(self, appbuilder, endpoint=None, static_folder=None):
"""
Create Flask blueprint. You will generally not use it
:param appbuilder:
the AppBuilder object
:param endpoint:
endpoint override for this blueprint,
will assume class name if not provided
:param static_folder:
the relative override for static folder,
if omitted application will use the appbuilder static
"""
# Store appbuilder instance
self.appbuilder = appbuilder
# If endpoint name is not provided, get it from the class name
self.endpoint = endpoint or self.__class__.__name__
if self.route_base is None:
self.route_base = "/" + self.__class__.__name__.lower()
self.static_folder = static_folder
if not static_folder:
# Create blueprint and register rules
self.blueprint = Blueprint(
self.endpoint,
__name__,
url_prefix=self.route_base,
template_folder=self.template_folder,
)
else:
self.blueprint = Blueprint(
self.endpoint,
__name__,
url_prefix=self.route_base,
template_folder=self.template_folder,
static_folder=static_folder,
)
self._register_urls()
return self.blueprint
def _register_urls(self):
before_request_hooks = get_before_request_hooks(self)
for attr_name in dir(self):
if (
self.include_route_methods is not None
and attr_name not in self.include_route_methods
):
continue
if attr_name in self.exclude_route_methods:
log.info(
f"Not registering route for method "
f"{self.__class__.__name__}.{attr_name}"
)
continue
attr = getattr(self, attr_name)
if hasattr(attr, "_urls"):
for url, methods in attr._urls:
log.info(
f"Registering route {self.blueprint.url_prefix}{url} {methods}"
)
route_handler = wrap_route_handler_with_hooks(
attr_name, attr, before_request_hooks
)
self.blueprint.add_url_rule(
url, attr_name, route_handler, methods=methods
)
def render_template(self, template, **kwargs):
"""
Use this method on your own endpoints, will pass the extra_args
to the templates.
:param template: The template relative path
:param kwargs: arguments to be passed to the template
"""
kwargs["base_template"] = self.appbuilder.base_template
kwargs["appbuilder"] = self.appbuilder
return render_template(
template, **dict(list(kwargs.items()) + list(self.extra_args.items()))
)
def _prettify_name(self, name):
"""
Prettify pythonic variable name.
For example, 'HelloWorld' will be converted to 'Hello World'
:param name:
Name to prettify.
"""
return re.sub(r"(?<=.)([A-Z])", r" \1", name)
def _prettify_column(self, name):
"""
Prettify pythonic variable name.
For example, 'hello_world' will be converted to 'Hello World'
:param name:
Name to prettify.
"""
return re.sub("[._]", " ", name).title()
def update_redirect(self):
"""
Call it on your own endpoint's to update the back history navigation.
If you bypass it, the next submit or back will go over it.
"""
page_history = Stack(session.get("page_history", []))
page_history.push(request.url)
session["page_history"] = page_history.to_json()
def get_redirect(self):
"""
Returns the previous url.
"""
index_url = self.appbuilder.get_url_for_index
page_history = Stack(session.get("page_history", []))
if page_history.pop() is None:
return index_url
session["page_history"] = page_history.to_json()
url = page_history.pop() or index_url
return url
@classmethod
def get_default_url(cls, **kwargs):
"""
Returns the url for this class default endpoint
"""
return url_for(cls.__name__ + "." + cls.default_view, **kwargs)
def get_uninit_inner_views(self):
"""
Will return a list with views that need to be initialized.
Normally related_views from ModelView
"""
return []
def get_init_inner_views(self, views):
"""
Sets initialized inner views
"""
pass
def get_method_permission(self, method_name: str) -> str:
"""
Returns the permission name for a method
"""
permission = self.method_permission_name.get(method_name)
if permission:
return permission
else:
return getattr(getattr(self, method_name), "_permission_name")
class BaseFormView(BaseView):
"""
Base class FormView's
"""
form_template = "appbuilder/general/model/edit.html"
edit_widget = FormWidget
""" Form widget to override """
form_title = ""
""" The form title to be displayed """
form_columns = None
""" The form columns to include, if empty will include all"""
form = None
""" The WTF form to render """
form_fieldsets = None
""" Form field sets """
default_view = "this_form_get"
""" The form view default entry endpoint """
def _init_vars(self):
self.form_columns = self.form_columns or []
self.form_fieldsets = self.form_fieldsets or []
list_cols = [field.name for field in self.form.refresh()]
if self.form_fieldsets:
self.form_columns = []
for fieldset_item in self.form_fieldsets:
self.form_columns = self.form_columns + list(
fieldset_item[1].get("fields")
)
else:
if not self.form_columns:
self.form_columns = list_cols
def form_get(self, form):
"""
Override this method to implement your form processing
"""
pass
def form_post(self, form):
"""
Override this method to implement your form processing
:param form: WTForm form
Return None or a flask response to render
a custom template or redirect the user
"""
pass
def _get_edit_widget(self, form=None, exclude_cols=None, widgets=None):
exclude_cols = exclude_cols or []
widgets = widgets or {}
widgets["edit"] = self.edit_widget(
route_base=self.route_base,
form=form,
include_cols=self.form_columns,
exclude_cols=exclude_cols,
fieldsets=self.form_fieldsets,
)
return widgets
class BaseModelView(BaseView):
"""
The base class of ModelView and ChartView, all properties are inherited
Customize ModelView and ChartView overriding this properties
This class supports all the basics for query
"""
datamodel = None
"""
Your sqla model you must initialize it like::
class MyView(ModelView):
datamodel = SQLAInterface(MyTable)
"""
title = "Title"
search_columns = None
"""
List with allowed search columns, if not provided
all possible search columns will be used
If you want to limit the search (*filter*) columns possibilities,
define it with a list of column names from your model::
class MyView(ModelView):
datamodel = SQLAInterface(MyTable)
search_columns = ['name','address']
"""
search_exclude_columns = None
"""
List with columns to exclude from search.
Search includes all possible columns by default
"""
search_form_extra_fields = None
"""
A dictionary containing column names and a WTForm
Form fields to be added to the search form, these fields do not
exist on the model itself ex::
search_form_extra_fields = {'some_col':BooleanField('Some Col', default=False)}
"""
search_form_query_rel_fields = None
"""
Add Customized query for related fields on search form.
Assign a dictionary where the keys are the column names of
the related models to filter, the value for each key, is a list of lists with the
same format as base_filter
{'relation col name':[['Related model col',FilterClass,'Filter Value'],...],...}
Add a custom filter to form related fields::
class ContactModelView(ModelView):
datamodel = SQLAModel(Contact, db.session)
search_form_query_rel_fields = {'group':[['name',FilterStartsWith,'W']]}
"""
label_columns = None
"""
Dictionary of labels for your columns,
override this if you want different pretify labels
example (will just override the label for name column)::
class MyView(ModelView):
datamodel = SQLAInterface(MyTable)
label_columns = {'name':'My Name Label Override'}
"""
search_form = None
""" To implement your own add WTF form for Search """
base_filters = None
"""
Filter the view use: [['column_name',BaseFilter,'value'],]
example::
def get_user():
return g.user
class MyView(ModelView):
datamodel = SQLAInterface(MyTable)
base_filters = [['created_by', FilterEqualFunction, get_user],
['name', FilterStartsWith, 'a']]
"""
base_order = None
"""
Use this property to set default ordering for lists ('col_name','asc|desc')::
class MyView(ModelView):
datamodel = SQLAInterface(MyTable)
base_order = ('my_column_name','asc')
"""
search_widget = SearchWidget
""" Search widget you can override with your own """
_base_filters = None
""" Internal base Filter from class Filters will always filter view """
_filters = None
""" Filters object will calculate all possible filter types
based on search_columns """
def __init__(self, **kwargs):
"""
Constructor
"""
datamodel = kwargs.get("datamodel", None)
if datamodel:
self.datamodel = datamodel
self._init_properties()
self._init_forms()
self._init_titles()
super(BaseModelView, self).__init__(**kwargs)
def _gen_labels_columns(self, list_columns):
"""
Auto generates pretty label_columns from list of columns
"""
for col in list_columns:
if not self.label_columns.get(col):
self.label_columns[col] = self._prettify_column(col)
def _init_titles(self):
pass
def _init_properties(self):
self.label_columns = self.label_columns or {}
self.base_filters = self.base_filters or []
self.search_exclude_columns = self.search_exclude_columns or []
self.search_columns = self.search_columns or []
self._base_filters = self.datamodel.get_filters().add_filter_list(
self.base_filters
)
list_cols = self.datamodel.get_columns_list()
search_columns = self.datamodel.get_search_columns_list()
if not self.search_columns:
self.search_columns = [
x for x in search_columns if x not in self.search_exclude_columns
]
self._gen_labels_columns(list_cols)
self._filters = self.datamodel.get_filters(self.search_columns)
def _init_forms(self):
conv = GeneralModelConverter(self.datamodel)
if not self.search_form:
self.search_form = conv.create_form(
self.label_columns,
self.search_columns,
extra_fields=self.search_form_extra_fields,
filter_rel_fields=self.search_form_query_rel_fields,
)
def _get_search_widget(self, form=None, exclude_cols=None, widgets=None):
exclude_cols = exclude_cols or []
widgets = widgets or {}
widgets["search"] = self.search_widget(
route_base=self.route_base,
form=form,
include_cols=self.search_columns,
exclude_cols=exclude_cols,
filters=self._filters,
)
return widgets
def _label_columns_json(self):
"""
Prepares dict with labels to be JSON serializable
"""
ret = {}
for key, value in list(self.label_columns.items()):
ret[key] = as_unicode(value.encode("UTF-8"))
return ret
class BaseCRUDView(BaseModelView):
"""
The base class for ModelView, all properties are inherited
Customize ModelView overriding this properties
"""
related_views = None
"""
List with ModelView classes
Will be displayed related with this one using relationship sqlalchemy property::
class MyView(ModelView):
datamodel = SQLAModel(Group, db.session)
related_views = [MyOtherRelatedView]
"""
_related_views = None
""" internal list with ref to instantiated view classes """
list_title = ""
""" List Title, if not configured the default is 'List ' with pretty model name """
show_title = ""
""" Show Title , if not configured the default is 'Show ' with pretty model name """
add_title = ""
""" Add Title , if not configured the default is 'Add ' with pretty model name """
edit_title = ""
""" Edit Title , if not configured the default is 'Edit ' with pretty model name """
list_columns = None
"""
A list of columns (or model's methods) to be displayed on the list view.
Use it to control the order of the display
"""
show_columns = None
"""
A list of columns (or model's methods) to be displayed on the show view.
Use it to control the order of the display
"""
add_columns = None
"""
A list of columns (or model's methods) to be displayed on the add form view.
Use it to control the order of the display
"""
edit_columns = None
"""
A list of columns (or model's methods) to be displayed on the edit form view.
Use it to control the order of the display
"""
show_exclude_columns = None
"""
A list of columns to exclude from the show view.
By default all columns are included.
"""
add_exclude_columns = None
"""
A list of columns to exclude from the add form.
By default all columns are included.
"""
edit_exclude_columns = None
"""
A list of columns to exclude from the edit form.
By default all columns are included.
"""
order_columns = None
""" Allowed order columns """
page_size = 25
"""
Use this property to change default page size
"""
show_fieldsets = None
"""
show fieldsets django style [(<'TITLE'|None>, {'fields':[<F1>,<F2>,...]}),....]
::
class MyView(ModelView):
datamodel = SQLAModel(MyTable, db.session)
show_fieldsets = [
('Summary', {
'fields': [
'name',
'address',
'group'
]
}
),
('Personal Info', {
'fields': [
'birthday',
'personal_phone'
],
'expanded':False
}
),
]
"""
add_fieldsets = None
"""
add fieldsets django style (look at show_fieldsets for an example)
"""
edit_fieldsets = None
"""
edit fieldsets django style (look at show_fieldsets for an example)
"""
description_columns = None
"""
Dictionary with column descriptions that will be shown on the forms::
class MyView(ModelView):
datamodel = SQLAModel(MyTable, db.session)
description_columns = {
'name': 'your models name column',
'address': 'the address column'
}
"""
validators_columns = None
""" Dictionary to add your own validators for forms """
formatters_columns = None
""" Dictionary of formatter used to format the display of columns
formatters_columns = {'some_date_col': lambda x: x.isoformat() }
"""
add_form_extra_fields = None
"""
A dictionary containing column names and a WTForm
Form fields to be added to the Add form, these fields do not
exist on the model itself ex::
add_form_extra_fields = {'some_col':BooleanField('Some Col', default=False)}
"""
edit_form_extra_fields = None
""" Dictionary to add extra fields to the Edit form using this property """
add_form_query_rel_fields = None
"""
Add Customized query for related fields to add form.
Assign a dictionary where the keys are the column names of
the related models to filter, the value for each key, is a list of lists with the
same format as base_filter
{
'relation col name':
[['Related model col', FilterClass, 'Filter Value'],...],...
}
Add a custom filter to form related fields::
class ContactModelView(ModelView):
datamodel = SQLAModel(Contact, db.session)
add_form_query_rel_fields = {'group': [['name', FilterStartsWith, 'W']]}
"""
edit_form_query_rel_fields = None
"""
Add Customized query for related fields to edit form.
Assign a dictionary where the keys are the column names of
the related models to filter, the value for each key, is a list of lists with the
same format as base_filter
{
'relation col name':
[['Related model col', FilterClass, 'Filter Value'],...],...
}
Add a custom filter to form related fields::
class ContactModelView(ModelView):
datamodel = SQLAModel(Contact, db.session)
edit_form_query_rel_fields = {'group':[['name',FilterStartsWith,'W']]}
"""
add_form = None
""" To implement your own, assign WTF form for Add """
edit_form = None
""" To implement your own, assign WTF form for Edit """
list_template = "appbuilder/general/model/list.html"
""" Your own add jinja2 template for list """
edit_template = "appbuilder/general/model/edit.html"
""" Your own add jinja2 template for edit """
add_template = "appbuilder/general/model/add.html"
""" Your own add jinja2 template for add """
show_template = "appbuilder/general/model/show.html"
""" Your own add jinja2 template for show """
list_widget = ListWidget
""" List widget override """
edit_widget = FormWidget
""" Edit widget override """
add_widget = FormWidget
""" Add widget override """
show_widget = ShowWidget
""" Show widget override """
actions = None
def __init__(self, **kwargs):
super(BaseCRUDView, self).__init__(**kwargs)
# collect and setup actions
self.actions = {}
for attr_name in dir(self):
func = getattr(self, attr_name)
if hasattr(func, "_action"):
action = ActionItem(*func._action, func=func)
permission_name = action.name
# Infer previous if not declared
if self.method_permission_name.get(attr_name):
if not self.previous_method_permission_name.get(attr_name):
self.previous_method_permission_name[attr_name] = action.name
permission_name = (
PERMISSION_PREFIX + self.method_permission_name.get(attr_name)
)
if permission_name not in self.base_permissions:
self.base_permissions.append(permission_name)
self.actions[action.name] = action
def _init_forms(self):
"""
Init forms for Add and Edit
"""
super(BaseCRUDView, self)._init_forms()
conv = GeneralModelConverter(self.datamodel)
if not self.add_form:
self.add_form = conv.create_form(
self.label_columns,
self.add_columns,
self.description_columns,
self.validators_columns,
self.add_form_extra_fields,
self.add_form_query_rel_fields,
)
if not self.edit_form:
self.edit_form = conv.create_form(
self.label_columns,
self.edit_columns,
self.description_columns,
self.validators_columns,
self.edit_form_extra_fields,
self.edit_form_query_rel_fields,
)
def _init_titles(self):
"""
Init Titles if not defined
"""
super(BaseCRUDView, self)._init_titles()
class_name = self.datamodel.model_name
if not self.list_title:
self.list_title = "List " + self._prettify_name(class_name)
if not self.add_title:
self.add_title = "Add " + self._prettify_name(class_name)
if not self.edit_title:
self.edit_title = "Edit " + self._prettify_name(class_name)
if not self.show_title:
self.show_title = "Show " + self._prettify_name(class_name)
self.title = self.list_title
def _init_properties(self):
"""
Init Properties
"""
super(BaseCRUDView, self)._init_properties()
# Reset init props
self.related_views = self.related_views or []
self._related_views = self._related_views or []
self.description_columns = self.description_columns or {}
self.validators_columns = self.validators_columns or {}
self.formatters_columns = self.formatters_columns or {}
self.add_form_extra_fields = self.add_form_extra_fields or {}
self.edit_form_extra_fields = self.edit_form_extra_fields or {}
self.show_exclude_columns = self.show_exclude_columns or []
self.add_exclude_columns = self.add_exclude_columns or []
self.edit_exclude_columns = self.edit_exclude_columns or []
# Generate base props
list_cols = self.datamodel.get_user_columns_list()
self.list_columns = self.list_columns or [list_cols[0]]
self._gen_labels_columns(self.list_columns)
self.order_columns = (
self.order_columns
or self.datamodel.get_order_columns_list(list_columns=self.list_columns)
)
if self.show_fieldsets:
self.show_columns = []
for fieldset_item in self.show_fieldsets:
self.show_columns = self.show_columns + list(
fieldset_item[1].get("fields")
)
else:
if not self.show_columns:
self.show_columns = [
x for x in list_cols if x not in self.show_exclude_columns
]
if self.add_fieldsets:
self.add_columns = []
for fieldset_item in self.add_fieldsets:
self.add_columns = self.add_columns + list(
fieldset_item[1].get("fields")
)
else:
if not self.add_columns:
self.add_columns = [
x for x in list_cols if x not in self.add_exclude_columns
]
if self.edit_fieldsets:
self.edit_columns = []
for fieldset_item in self.edit_fieldsets:
self.edit_columns = self.edit_columns + list(
fieldset_item[1].get("fields")
)
else:
if not self.edit_columns:
self.edit_columns = [
x for x in list_cols if x not in self.edit_exclude_columns
]
"""
-----------------------------------------------------
GET WIDGETS SECTION
-----------------------------------------------------
"""
def _get_related_view_widget(
self,
item,
related_view,
order_column="",
order_direction="",
page=None,
page_size=None,
):
fk = related_view.datamodel.get_related_fk(self.datamodel.obj)
filters = related_view.datamodel.get_filters()
# Check if it's a many to one model relation
if related_view.datamodel.is_relation_many_to_one(fk):
filters.add_filter_related_view(
fk,
self.datamodel.FilterRelationOneToManyEqual,
self.datamodel.get_pk_value(item),
)
# Check if it's a many to many model relation
elif related_view.datamodel.is_relation_many_to_many(fk):
filters.add_filter_related_view(
fk,
self.datamodel.FilterRelationManyToManyEqual,
self.datamodel.get_pk_value(item),
)
else:
if isclass(related_view) and issubclass(related_view, BaseView):
name = related_view.__name__
else:
name = related_view.__class__.__name__
log.error("Can't find relation on related view {0}".format(name))
return None
return related_view._get_view_widget(
filters=filters,
order_column=order_column,
order_direction=order_direction,
page=page,
page_size=page_size,
)
def _get_related_views_widgets(
self, item, orders=None, pages=None, page_sizes=None, widgets=None, **args
):
"""
:return:
Returns a dict with 'related_views' key with a list of
Model View widgets
"""
widgets = widgets or {}
widgets["related_views"] = []
for view in self._related_views:
if orders.get(view.__class__.__name__):
order_column, order_direction = orders.get(view.__class__.__name__)
else:
order_column, order_direction = "", ""
widgets["related_views"].append(
self._get_related_view_widget(
item,
view,
order_column,
order_direction,
page=pages.get(view.__class__.__name__),
page_size=page_sizes.get(view.__class__.__name__),
)
)
return widgets