g3w-admin-qplotly 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. g3w_admin_qplotly-0.0.1.dist-info/METADATA +52 -0
  2. g3w_admin_qplotly-0.0.1.dist-info/RECORD +139 -0
  3. g3w_admin_qplotly-0.0.1.dist-info/WHEEL +5 -0
  4. g3w_admin_qplotly-0.0.1.dist-info/licenses/LICENSE +373 -0
  5. g3w_admin_qplotly-0.0.1.dist-info/top_level.txt +1 -0
  6. qplotly/__init__.py +1 -0
  7. qplotly/admin.py +34 -0
  8. qplotly/api/__init__.py +0 -0
  9. qplotly/api/plots/__init__.py +0 -0
  10. qplotly/api/plots/views.py +211 -0
  11. qplotly/api/widgets/__init__.py +0 -0
  12. qplotly/api/widgets/permissions.py +79 -0
  13. qplotly/api/widgets/serializers.py +109 -0
  14. qplotly/api/widgets/views.py +287 -0
  15. qplotly/apiurls.py +132 -0
  16. qplotly/apps.py +11 -0
  17. qplotly/locale/bg/LC_MESSAGES/django.mo +0 -0
  18. qplotly/locale/bg/LC_MESSAGES/django.po +162 -0
  19. qplotly/locale/de/LC_MESSAGES/django.mo +0 -0
  20. qplotly/locale/de/LC_MESSAGES/django.po +126 -0
  21. qplotly/locale/de/LC_MESSAGES/djangojs.mo +0 -0
  22. qplotly/locale/de/LC_MESSAGES/djangojs.po +221 -0
  23. qplotly/locale/es/LC_MESSAGES/django.mo +0 -0
  24. qplotly/locale/es/LC_MESSAGES/django.po +151 -0
  25. qplotly/locale/es/LC_MESSAGES/djangojs.mo +0 -0
  26. qplotly/locale/es/LC_MESSAGES/djangojs.po +232 -0
  27. qplotly/locale/fi/LC_MESSAGES/django.mo +0 -0
  28. qplotly/locale/fi/LC_MESSAGES/django.po +126 -0
  29. qplotly/locale/fi/LC_MESSAGES/djangojs.mo +0 -0
  30. qplotly/locale/fi/LC_MESSAGES/djangojs.po +222 -0
  31. qplotly/locale/fr/LC_MESSAGES/django.mo +0 -0
  32. qplotly/locale/fr/LC_MESSAGES/django.po +160 -0
  33. qplotly/locale/fr/LC_MESSAGES/djangojs.mo +0 -0
  34. qplotly/locale/fr/LC_MESSAGES/djangojs.po +222 -0
  35. qplotly/locale/it/LC_MESSAGES/django.mo +0 -0
  36. qplotly/locale/it/LC_MESSAGES/django.po +163 -0
  37. qplotly/locale/it/LC_MESSAGES/djangojs.mo +0 -0
  38. qplotly/locale/it/LC_MESSAGES/djangojs.po +220 -0
  39. qplotly/locale/pl/LC_MESSAGES/django.mo +0 -0
  40. qplotly/locale/pl/LC_MESSAGES/django.po +129 -0
  41. qplotly/locale/pl/LC_MESSAGES/djangojs.mo +0 -0
  42. qplotly/locale/pl/LC_MESSAGES/djangojs.po +217 -0
  43. qplotly/locale/pt/LC_MESSAGES/django.mo +0 -0
  44. qplotly/locale/pt/LC_MESSAGES/django.po +160 -0
  45. qplotly/locale/ro/LC_MESSAGES/django.mo +0 -0
  46. qplotly/locale/ro/LC_MESSAGES/django.po +128 -0
  47. qplotly/locale/ro/LC_MESSAGES/djangojs.mo +0 -0
  48. qplotly/locale/ro/LC_MESSAGES/djangojs.po +222 -0
  49. qplotly/locale/se/LC_MESSAGES/django.mo +0 -0
  50. qplotly/locale/se/LC_MESSAGES/django.po +126 -0
  51. qplotly/locale/se/LC_MESSAGES/djangojs.mo +0 -0
  52. qplotly/locale/se/LC_MESSAGES/djangojs.po +222 -0
  53. qplotly/migrations/0001_initial.py +26 -0
  54. qplotly/migrations/0002_qplotlywidget_type.py +18 -0
  55. qplotly/migrations/0003_auto_20200925_0838.py +18 -0
  56. qplotly/migrations/0004_auto_20200925_1535.py +25 -0
  57. qplotly/migrations/0005_qplotlywidget_show_on_start_client.py +18 -0
  58. qplotly/migrations/0006_alter_qplotlywidget_options_qplotlywidget_order.py +23 -0
  59. qplotly/migrations/0007_alter_qplotlywidget_options_and_more.py +22 -0
  60. qplotly/migrations/0008_alter_qplotlywidget_order.py +18 -0
  61. qplotly/migrations/0009_qplotlywidget_show_in_sidebar.py +18 -0
  62. qplotly/migrations/0010_remove_qplotlywidget_show_in_sidebar_and_more.py +22 -0
  63. qplotly/migrations/0011_rename_show_poistion_qplotlywidget_show_position.py +18 -0
  64. qplotly/migrations/0012_qplotlywidgetrelation_qplotlywidget_related_widgets.py +34 -0
  65. qplotly/migrations/0013_alter_qplotlywidgetrelation_source_and_more.py +24 -0
  66. qplotly/migrations/0014_alter_qplotlywidgetrelation_source_and_more.py +24 -0
  67. qplotly/migrations/0015_qplotlywidgetrelation_project.py +34 -0
  68. qplotly/migrations/0016_remove_qplotlywidget_project.py +17 -0
  69. qplotly/migrations/__init__.py +0 -0
  70. qplotly/models.py +142 -0
  71. qplotly/receivers.py +356 -0
  72. qplotly/requirements.txt +1 -0
  73. qplotly/server_filters/__init__.py +1 -0
  74. qplotly/server_filters/relations.py +32 -0
  75. qplotly/static/qplotly/icons/2dhistogram.svg +2048 -0
  76. qplotly/static/qplotly/icons/barplot.svg +2048 -0
  77. qplotly/static/qplotly/icons/boxplot.svg +2048 -0
  78. qplotly/static/qplotly/icons/contour.svg +2056 -0
  79. qplotly/static/qplotly/icons/histogram.svg +2048 -0
  80. qplotly/static/qplotly/icons/pie.svg +2048 -0
  81. qplotly/static/qplotly/icons/polar.svg +2055 -0
  82. qplotly/static/qplotly/icons/scatterplot.svg +2048 -0
  83. qplotly/static/qplotly/icons/scatterternary.svg +2055 -0
  84. qplotly/static/qplotly/icons/violin.svg +2878 -0
  85. qplotly/static/qplotly/js/data-widget-qplotlyWidgetList.js +373 -0
  86. qplotly/static/qplotly/js/i18n/bg.js +19 -0
  87. qplotly/static/qplotly/js/i18n/de.js +19 -0
  88. qplotly/static/qplotly/js/i18n/en.js +19 -0
  89. qplotly/static/qplotly/js/i18n/fi.js +19 -0
  90. qplotly/static/qplotly/js/i18n/fr.js +19 -0
  91. qplotly/static/qplotly/js/i18n/index.js +19 -0
  92. qplotly/static/qplotly/js/i18n/it.js +19 -0
  93. qplotly/static/qplotly/js/i18n/ro.js +19 -0
  94. qplotly/static/qplotly/js/i18n/se.js +19 -0
  95. qplotly/static/qplotly/js/i18n/uk.js +19 -0
  96. qplotly/static/qplotly/js/plugin.js +927 -0
  97. qplotly/static/qplotly/js/sidebar.js +373 -0
  98. qplotly/static/qplotly/js/widget.js +9 -0
  99. qplotly/static/qplotly/plotly-1.52.2.min.js +7 -0
  100. qplotly/static/qplotly/polyfill.min.js +3 -0
  101. qplotly/templates/qplotly/include/plot_type_icon.html +52 -0
  102. qplotly/templates/qplotly/layer_action.html +13 -0
  103. qplotly/templates/qplotly/plots_list_order.html +68 -0
  104. qplotly/templates/qplotly/plots_list_order_action.html +14 -0
  105. qplotly/templatetags/__init__.py +0 -0
  106. qplotly/templatetags/qplotly_tags.py +28 -0
  107. qplotly/urls.py +52 -0
  108. qplotly/utils/__init__.py +13 -0
  109. qplotly/utils/models.py +86 -0
  110. qplotly/utils/qplotly_factory.py +699 -0
  111. qplotly/utils/qplotly_settings.py +37 -0
  112. qplotly/vendor/DataPlotly/__init__.py +0 -0
  113. qplotly/vendor/DataPlotly/core/__init__.py +0 -0
  114. qplotly/vendor/DataPlotly/core/plot_factory.py +843 -0
  115. qplotly/vendor/DataPlotly/core/plot_settings.py +322 -0
  116. qplotly/vendor/DataPlotly/core/plot_types/__init__.py +20 -0
  117. qplotly/vendor/DataPlotly/core/plot_types/bar_plot.py +83 -0
  118. qplotly/vendor/DataPlotly/core/plot_types/box.py +56 -0
  119. qplotly/vendor/DataPlotly/core/plot_types/contour.py +43 -0
  120. qplotly/vendor/DataPlotly/core/plot_types/histogram.py +66 -0
  121. qplotly/vendor/DataPlotly/core/plot_types/histogram2d.py +39 -0
  122. qplotly/vendor/DataPlotly/core/plot_types/icons/2dhistogram.svg +2048 -0
  123. qplotly/vendor/DataPlotly/core/plot_types/icons/barplot.svg +2048 -0
  124. qplotly/vendor/DataPlotly/core/plot_types/icons/boxplot.svg +2048 -0
  125. qplotly/vendor/DataPlotly/core/plot_types/icons/contour.svg +2056 -0
  126. qplotly/vendor/DataPlotly/core/plot_types/icons/histogram.svg +2048 -0
  127. qplotly/vendor/DataPlotly/core/plot_types/icons/pie.svg +2048 -0
  128. qplotly/vendor/DataPlotly/core/plot_types/icons/polar.svg +2055 -0
  129. qplotly/vendor/DataPlotly/core/plot_types/icons/scatterplot.svg +2048 -0
  130. qplotly/vendor/DataPlotly/core/plot_types/icons/scatterternary.svg +2055 -0
  131. qplotly/vendor/DataPlotly/core/plot_types/icons/violin.svg +2878 -0
  132. qplotly/vendor/DataPlotly/core/plot_types/pie.py +60 -0
  133. qplotly/vendor/DataPlotly/core/plot_types/plot_type.py +170 -0
  134. qplotly/vendor/DataPlotly/core/plot_types/polar.py +63 -0
  135. qplotly/vendor/DataPlotly/core/plot_types/scatter.py +74 -0
  136. qplotly/vendor/DataPlotly/core/plot_types/ternary.py +129 -0
  137. qplotly/vendor/DataPlotly/core/plot_types/violin.py +62 -0
  138. qplotly/vendor/__init__.py +0 -0
  139. qplotly/views.py +148 -0
@@ -0,0 +1,211 @@
1
+ # coding=utf-8
2
+ """" Qplotly api views
3
+
4
+ .. note:: This program is free software; you can redistribute it and/or modify
5
+ it under the terms of the Mozilla Public License 2.0.
6
+
7
+ """
8
+
9
+ __author__ = 'lorenzetti@gis3w.it'
10
+ __date__ = '2020-09-17'
11
+ __copyright__ = 'Copyright 2015 - 2020, Gis3w'
12
+
13
+ from qgis.core import \
14
+ QgsRectangle, \
15
+ QgsReferencedRectangle, \
16
+ QgsCoordinateReferenceSystem
17
+ from rest_framework.response import Response
18
+ from core.api.base.views import G3WAPIView
19
+ from core.utils.qgisapi import get_qgis_layer, get_qgs_project
20
+ from qdjango.models import Layer
21
+ from qplotly.models import QplotlyWidget
22
+ from qplotly.utils.qplotly_settings import QplotlySettings
23
+ from qplotly.utils.qplotly_factory import QplotlyFactoring, QplotlyFactoringRelation
24
+ import plotly
25
+ import plotly.graph_objects as go
26
+
27
+
28
+ import logging
29
+
30
+ logger = logging.getLogger('module_qplotly')
31
+
32
+
33
+ WITH_RELATIONS_PARAM = 'withrelations'
34
+
35
+
36
+ class QplotlyTraceAPIView(G3WAPIView):
37
+ """API return plotly trace data"""
38
+
39
+ def _get_trace(self, factory):
40
+ """
41
+ Private method to get trace data by plotly version
42
+ :param factory: QplotlyFactoring or QplotlyFactoringRelation instance
43
+ :return: Trace data as dict
44
+ :return type: dict
45
+ """
46
+
47
+ if plotly.__version__ != '2.5.1':
48
+ fig = go.Figure(layout=factory.layout)
49
+ fig.add_trace(factory.trace[0])
50
+ data = fig.to_dict()['data']
51
+ else:
52
+ data = factory.trace
53
+
54
+ return data
55
+
56
+ def _get_relations(self, with_relations=[], flayer=None, ffactory=None, request=None, res={}):
57
+ """
58
+ Check for relations adn add to res
59
+ :param with_relations: relations id list
60
+ :param source_layer: QgsVectorLayer instance of father
61
+ :param res: result dict to send into response
62
+ """
63
+
64
+ qgs_prj = get_qgs_project(flayer.project.qgis_file.path)
65
+
66
+ relations = None
67
+ for relation_id in with_relations:
68
+ qgs_relation = qgs_prj.relationManager().relation(relation_id)
69
+ if not qgs_relation.isValid():
70
+ logger.error(f'Relation with id {relation_id} is not valid.')
71
+ continue
72
+
73
+ csource_layer = qgs_relation.referencingLayer()
74
+ clayer = flayer.project.layer_set.get(qgs_layer_id=csource_layer.id())
75
+
76
+ # get every qplotly active for child layer
77
+ qplotlies = clayer.qplotlywidget_set.all()
78
+ if len(qplotlies) == 0:
79
+ continue
80
+
81
+ if not relations:
82
+ relations = {
83
+ relation_id: []
84
+ }
85
+ else:
86
+ relations.update({
87
+ relation_id: []
88
+ })
89
+
90
+ for qplotly in qplotlies:
91
+ settings = QplotlySettings()
92
+ if not settings.read_from_model(qplotly):
93
+ logger.error(f'Error on load qlotly settings for layer pk {clayer.pk}.')
94
+ continue
95
+
96
+ factory = QplotlyFactoringRelation(settings, request=request, layer=clayer)
97
+ factory.source_layer = csource_layer
98
+
99
+ # create expression
100
+ ffiltered_features = ffactory.source_layer.getFeatures(ffactory.qgsrequest)
101
+ factory.set_father_features_expresion(qgs_relation=qgs_relation,
102
+ ffiltered_features=ffiltered_features)
103
+
104
+ factory.rebuild()
105
+
106
+ relations[relation_id].append({
107
+ 'id': qplotly.pk,
108
+ 'data': self._get_trace(factory)
109
+ })
110
+
111
+ if 'relations' not in res and relations:
112
+ res.update({'relations': relations})
113
+
114
+ def get(self, request, **kwargs):
115
+
116
+ qplotly = QplotlyWidget.objects.get(pk=kwargs['pk'])
117
+
118
+ # load settings from db
119
+ settings = QplotlySettings()
120
+ if not settings.read_from_model(qplotly):
121
+ raise Exception()
122
+
123
+ # patch for xml setting linked to layer with same datasource.
124
+ qgs_layer_id = kwargs['qgs_layer_id'] if 'qgs_layer_id' in kwargs else settings.source_layer_id
125
+
126
+ # get bbox if is sent
127
+ # 2021/01/12 using IntersectBBOXFilter
128
+ rect = None
129
+ #if 'bbox' in kwargs:
130
+ # rect = QgsReferencedRectangle(QgsRectangle(**kwargs['bbox']),
131
+ # QgsCoordinateReferenceSystem(qplotly.project.group.srid.srid))
132
+
133
+ # instance a QplotlyFactory
134
+ layer = Layer.objects.get(qgs_layer_id=qgs_layer_id, project_id=kwargs['project_id'])
135
+ factory = QplotlyFactoring(settings, visible_region=rect, request=request, layer=layer)
136
+
137
+
138
+ # If possible get the first layer
139
+ factory.source_layer = get_qgis_layer(qplotly.layers.get(qgs_layer_id=settings.source_layer_id,
140
+ project_id=kwargs['project_id']))
141
+ factory.rebuild()
142
+
143
+ res = {
144
+ 'data': self._get_trace(factory)
145
+ }
146
+
147
+ # if withrelations was sent add relations trace values
148
+ # ----------------------------------------------------
149
+ if request.method == 'POST':
150
+ request_data = request.data
151
+ else:
152
+ request_data = request.query_params
153
+
154
+ with_relations = request_data.get(WITH_RELATIONS_PARAM)
155
+
156
+ if with_relations:
157
+ self._get_relations(
158
+ with_relations=with_relations.split(','),
159
+ flayer=layer,
160
+ ffactory=factory,
161
+ request=request,
162
+ res=res,
163
+ )
164
+
165
+ self.results.results.update(res)
166
+
167
+ return Response(self.results.results)
168
+
169
+
170
+
171
+ class QplotlyTraceConfigAPIView(G3WAPIView):
172
+ """API return plotly trace config data
173
+ .. note:: This is used to get the trace config data for a plotly widget.
174
+ """
175
+
176
+ def get(self, request, **kwargs):
177
+ """Get the trace config data for a plotly widget."""
178
+ qplotly = QplotlyWidget.objects.get(pk=kwargs['pk'])
179
+
180
+ # load settings from db
181
+ settings = QplotlySettings()
182
+ if not settings.read_from_model(qplotly):
183
+ raise Exception()
184
+
185
+ # instance a QplotlyFactory
186
+ factory = QplotlyFactoring(settings, request=request, layer=None)
187
+ #factory.build_layout()
188
+
189
+ fig = go.Figure(layout=factory.layout)
190
+ layout = fig.to_dict()['layout']
191
+
192
+ res = {
193
+ 'data':{
194
+ 'type': settings.plot_type,
195
+ 'layout': layout,
196
+ 'config': {
197
+ 'displaylogo': False,
198
+ 'displayModeBar': True,
199
+ 'modeBarButtonsToRemove': ['sendDataToCloud', 'editInChartStudio'],
200
+ 'editable': True,
201
+ 'responsive': True,
202
+ 'scrollZoom': False,
203
+ 'toImageButtonOptions': {'filename': 'Plot - ' + layout.get('title', {}).get('text', f"[{qplotly.pk}]") },
204
+ 'autosize': True,
205
+ }
206
+ }
207
+ }
208
+
209
+ self.results.results.update(res)
210
+
211
+ return Response(self.results.results)
File without changes
@@ -0,0 +1,79 @@
1
+ # coding=utf-8
2
+ """"
3
+
4
+ .. note:: This program is free software; you can redistribute it and/or modify
5
+ it under the terms of the Mozilla Public License 2.0.
6
+
7
+ """
8
+
9
+ __author__ = 'lorenzetti@gis3w.it'
10
+ __date__ = '2020-09-23'
11
+ __copyright__ = 'Copyright 2015 - 2020, Gis3w'
12
+
13
+ from django.core.exceptions import ObjectDoesNotExist
14
+ from rest_framework.permissions import BasePermission
15
+ from qdjango.models.projects import Layer
16
+ from qplotly.models import QplotlyWidget
17
+
18
+
19
+ class QplotlyWidgetPermission(BasePermission):
20
+ """
21
+ API permission for Qplotly urls
22
+ Allows access only to users have permission change_project on project
23
+ """
24
+
25
+ def has_permission(self, request, view):
26
+
27
+ # case every constraint only for admin user
28
+ if request.user.is_superuser:
29
+ return True
30
+
31
+ try:
32
+ if request.method in ('POST'):
33
+ if 'layer' in request.POST:
34
+ # case Constraint API list
35
+ layer = Layer.objects.get(pk=request.POST['layer'])
36
+ elif 'layer_id' in view.kwargs:
37
+ layer = Layer.objects.get(pk=view.kwargs['layer_id'])
38
+ else:
39
+ return False
40
+
41
+ else:
42
+ # case: GET, PUT, DELETE
43
+ if 'pk' in view.kwargs and 'project_id' in view.kwargs:
44
+ # for this controll is necessary have project_id
45
+ layer = QplotlyWidget.objects.get(pk=view.kwargs['pk']).\
46
+ layers.filter(project_id=view.kwargs['project_id'])[0]
47
+ elif 'layer_id' in view.kwargs:
48
+ layer = Layer.objects.get(id=view.kwargs['layer_id'])
49
+ else:
50
+ return False
51
+
52
+ # check change_layer permission on qgis layer
53
+ return request.user.has_perm('qdjango.change_project', layer.project)
54
+
55
+ except ObjectDoesNotExist:
56
+ return False
57
+
58
+
59
+ class QplotlyWidgetRelatedPermission(BasePermission):
60
+ """
61
+ API permission for related_widgets management on a QplotlyWidget.
62
+ Resolves the project from the source widget (pk) and project_id kwargs.
63
+ Allows access only to users with change_project permission on the related project.
64
+ """
65
+
66
+ def has_permission(self, request, view):
67
+
68
+ if request.user.is_superuser:
69
+ return True
70
+
71
+ try:
72
+ widget = QplotlyWidget.objects.get(pk=view.kwargs['pk'])
73
+ layer = widget.layers.first()
74
+ if layer is None:
75
+ return False
76
+ return request.user.has_perm('qdjango.change_project', layer.project)
77
+
78
+ except (ObjectDoesNotExist, KeyError):
79
+ return False
@@ -0,0 +1,109 @@
1
+ # coding=utf-8
2
+ """" Qplotly widgets API serializers
3
+
4
+ .. note:: This program is free software; you can redistribute it and/or modify
5
+ it under the terms of the Mozilla Public License 2.0.
6
+
7
+ """
8
+
9
+ __author__ = 'lorenzetti@gis3w.it'
10
+ __date__ = '2020-09-23'
11
+ __copyright__ = 'Copyright 2015 - 2020, Gis3w'
12
+
13
+ from rest_framework import serializers
14
+ from django.utils.translation import gettext_lazy as _
15
+ from rest_framework.fields import empty
16
+
17
+ from qdjango.models import Layer
18
+ from qplotly.models import QplotlyWidget
19
+ from qplotly.utils.qplotly_settings import QplotlySettings
20
+
21
+
22
+ class QplotlyWidgetCleanValidator(object):
23
+ """Validates the qplotly widget instance by calling model's clean()"""
24
+
25
+ def __call__(self, value):
26
+ try:
27
+ QplotlyWidget(
28
+ xml=value['xml']
29
+ ).clean()
30
+ except Exception as ex:
31
+ raise serializers.ValidationError(str(ex))
32
+
33
+
34
+ class QplotlyWidgetLayersValidator(object):
35
+ """Validates the qplotly widget layers"""
36
+
37
+ def __call__(self, value):
38
+ try:
39
+ settings = QplotlySettings()
40
+ settings.read_from_model(QplotlyWidget(xml=value['xml']))
41
+ layers = Layer.objects.filter(pk__in=[l.pk for l in value['layers']])
42
+ for layer in layers:
43
+ if layer.qgs_layer_id != settings.source_layer_id:
44
+ raise Exception(
45
+ _(f'Layer with id {layer.qgs_layer_id} is no equal to setting {settings.source_layer_id}'))
46
+
47
+ except Exception as ex:
48
+ raise serializers.ValidationError(ex)
49
+
50
+
51
+ class QplotlyWidgetSerializer(serializers.ModelSerializer):
52
+
53
+ class Meta:
54
+ model = QplotlyWidget
55
+
56
+ fields = [
57
+ 'pk',
58
+ 'xml',
59
+ 'datasource',
60
+ 'selected_features_only',
61
+ 'visible_features_only',
62
+ 'type',
63
+ 'title',
64
+ 'layers',
65
+ 'show_on_start_client',
66
+ 'show_position',
67
+ ]
68
+
69
+ validators = [
70
+ QplotlyWidgetCleanValidator(),
71
+ QplotlyWidgetLayersValidator()
72
+ ]
73
+
74
+ def _get_validate_data_from_settings(self, validate_data):
75
+ """Fill validate_dat with value not sent"""
76
+
77
+ settings = QplotlySettings()
78
+ settings.read_from_model(QplotlyWidget(xml=validate_data['xml']))
79
+
80
+ if 'datasource' not in validate_data:
81
+ validate_data['datasource'] = validate_data['layers'][0].datasource
82
+
83
+ if 'type' not in validate_data:
84
+ validate_data['type'] = settings.plot_type
85
+
86
+ if 'title' not in validate_data:
87
+ validate_data['title'] = settings.layout['title']
88
+
89
+ def create(self, validated_data):
90
+ self._get_validate_data_from_settings(validated_data)
91
+ return super().create(validated_data=validated_data)
92
+
93
+ def update(self, instance, validated_data):
94
+ self._get_validate_data_from_settings(validated_data)
95
+ return super().update(instance=instance, validated_data=validated_data)
96
+
97
+ def to_representation(self, instance):
98
+
99
+ ret = super().to_representation(instance)
100
+
101
+ # add layers qgs_layer_id
102
+ try:
103
+ ret['project'] = self.context['project'].pk
104
+ except Exception:
105
+ pass
106
+
107
+ return ret
108
+
109
+
@@ -0,0 +1,287 @@
1
+ # coding=utf-8
2
+ """" API qplotly widgets
3
+
4
+ .. note:: This program is free software; you can redistribute it and/or modify
5
+ it under the terms of the Mozilla Public License 2.0.
6
+
7
+ """
8
+
9
+ __author__ = 'lorenzetti@gis3w.it'
10
+ __date__ = '2020-09-23'
11
+ __copyright__ = 'Copyright 2015 - 2020, Gis3w'
12
+
13
+ from rest_framework import generics, status
14
+ from rest_framework.views import APIView
15
+ from rest_framework.response import Response
16
+
17
+ from django.db.models import F
18
+ from django.http import Http404
19
+
20
+ from core.api.authentication import CsrfExemptSessionAuthentication
21
+
22
+ from qplotly.models import QplotlyWidget, QplotlyWidgetRelation
23
+ from qplotly.utils.models import get_qplotlywidgets4layer
24
+
25
+ from qdjango.models import Layer, Project
26
+
27
+ from .serializers import QplotlyWidgetSerializer
28
+ from .permissions import QplotlyWidgetPermission, QplotlyWidgetRelatedPermission
29
+
30
+
31
+ class QplotlyWidgetList(generics.ListCreateAPIView):
32
+ """List of qplotly widgets, optionally filtered by editing layer id"""
33
+
34
+ queryset = QplotlyWidget.objects.all()
35
+ serializer_class = QplotlyWidgetSerializer
36
+
37
+ pagination_class = None
38
+
39
+ authentication_classes = (
40
+ CsrfExemptSessionAuthentication,
41
+ )
42
+
43
+ permission_classes = (
44
+ QplotlyWidgetPermission,
45
+ )
46
+
47
+ def get_serializer_context(self):
48
+ """
49
+ Extra context provided to the serializer class.
50
+ """
51
+
52
+ toret = super().get_serializer_context()
53
+ toret['project'] = self.layer.project if hasattr(self, 'layer') else None
54
+ return toret
55
+
56
+
57
+ def get_queryset(self):
58
+ """
59
+ This view should return a list constraints for a given layer id portion of the URL.
60
+ """
61
+
62
+ qs = super().get_queryset()
63
+ if 'layer_id' in self.kwargs:
64
+ self.layer = Layer.objects.filter(pk=self.kwargs['layer_id']).first()
65
+ qs = get_qplotlywidgets4layer(self.layer)
66
+ return qs
67
+
68
+
69
+ class QplotlyWidgetDetail(generics.RetrieveUpdateDestroyAPIView):
70
+ """Details/Update/Delete of a qplotly widget"""
71
+
72
+ queryset = QplotlyWidget.objects.all()
73
+ serializer_class = QplotlyWidgetSerializer
74
+
75
+ authentication_classes = (
76
+ CsrfExemptSessionAuthentication,
77
+ )
78
+
79
+ permission_classes = (
80
+ QplotlyWidgetPermission,
81
+ )
82
+
83
+
84
+ class QplotlyWidgetRelatedWidgetView(APIView):
85
+ """
86
+ Manage related_widgets on a QplotlyWidget via the QplotlyWidgetRelation through-model.
87
+
88
+ GET /api/widget/related/<pk>/<project_id>/
89
+ Returns the list of related widgets with their relation order.
90
+
91
+ POST /api/widget/related/<pk>/
92
+ Adds a relation. Body: {"target": <widget_id>, "project": <project_id>, "order": <int>}
93
+ Creates the relation if it does not exist, otherwise updates the order.
94
+
95
+ DELETE /api/widget/related/<pk>/<target_pk>/<project_id>/
96
+ Removes the relation between the source widget and the target widget.
97
+ """
98
+
99
+ authentication_classes = (CsrfExemptSessionAuthentication,)
100
+ permission_classes = (QplotlyWidgetRelatedPermission,)
101
+
102
+ def _get_widget_or_404(self, pk):
103
+ try:
104
+ return QplotlyWidget.objects.get(pk=pk)
105
+ except QplotlyWidget.DoesNotExist:
106
+ raise Http404
107
+
108
+ def get(self, request, pk, project_id=None):
109
+ widget = self._get_widget_or_404(pk)
110
+
111
+ if project_id is None:
112
+ return Response(
113
+ {'error': "'project_id' path parameter is required"},
114
+ status=status.HTTP_400_BAD_REQUEST,
115
+ )
116
+
117
+ relations = widget.widget_relations.select_related('target').filter(project_id=project_id)
118
+ data = [
119
+ {
120
+ 'id': r.target.pk,
121
+ 'title': r.target.title,
122
+ 'type': r.target.type,
123
+ 'order': r.order,
124
+ }
125
+ for r in relations
126
+ ]
127
+ return Response(data)
128
+
129
+ def post(self, request, pk):
130
+ widget = self._get_widget_or_404(pk)
131
+ target_id = request.data.get('target')
132
+ project_id = request.data.get('project')
133
+ order = request.data.get('order', 0)
134
+
135
+ if not target_id:
136
+ return Response(
137
+ {'error': "'target' field is required"},
138
+ status=status.HTTP_400_BAD_REQUEST,
139
+ )
140
+
141
+ if not project_id:
142
+ return Response(
143
+ {'error': "'project' field is required"},
144
+ status=status.HTTP_400_BAD_REQUEST,
145
+ )
146
+
147
+ try:
148
+ target_id = int(target_id)
149
+ except (TypeError, ValueError):
150
+ return Response(
151
+ {'error': "'target' must be a valid widget id"},
152
+ status=status.HTTP_400_BAD_REQUEST,
153
+ )
154
+
155
+ try:
156
+ project_id = int(project_id)
157
+ except (TypeError, ValueError):
158
+ return Response(
159
+ {'error': "'project' must be a valid project id"},
160
+ status=status.HTTP_400_BAD_REQUEST,
161
+ )
162
+
163
+ if not Project.objects.filter(pk=project_id).exists():
164
+ return Response(
165
+ {'error': f'Project with pk={project_id} not found'},
166
+ status=status.HTTP_404_NOT_FOUND,
167
+ )
168
+
169
+ try:
170
+ target = QplotlyWidget.objects.get(pk=target_id)
171
+ except QplotlyWidget.DoesNotExist:
172
+ return Response(
173
+ {'error': f'Widget with pk={target_id} not found'},
174
+ status=status.HTTP_404_NOT_FOUND,
175
+ )
176
+
177
+ relation, created = QplotlyWidgetRelation.objects.get_or_create(
178
+ source=widget,
179
+ target=target,
180
+ project_id=project_id,
181
+ defaults={'order': order},
182
+ )
183
+ if not created:
184
+ relation.order = order
185
+ relation.save(update_fields=['order'])
186
+
187
+ return Response(
188
+ {'id': target.pk, 'order': relation.order},
189
+ status=status.HTTP_201_CREATED if created else status.HTTP_200_OK,
190
+ )
191
+
192
+ def delete(self, request, pk, target_pk, project_id):
193
+ widget = self._get_widget_or_404(pk)
194
+
195
+ deleted, _ = QplotlyWidgetRelation.objects.filter(
196
+ source=widget,
197
+ target_id=target_pk,
198
+ project_id=project_id,
199
+ ).delete()
200
+ if deleted == 0:
201
+ return Response(status=status.HTTP_404_NOT_FOUND)
202
+ return Response(status=status.HTTP_204_NO_CONTENT)
203
+
204
+
205
+ class QplotlyWidgetRelatedWidgetPostView(QplotlyWidgetRelatedWidgetView):
206
+ """POST-only endpoint for creating/updating related widget relations."""
207
+
208
+ http_method_names = ['post', 'options']
209
+
210
+
211
+ class QplotlyWidgetAvailableRelatedView(APIView):
212
+ """
213
+ GET /api/widget/related/<pk>/available/<project_id>/
214
+ Returns widgets that can be added as related to the widget <pk>:
215
+ - belong to the same layer(s) as <pk>
216
+ - are not already a target of any QplotlyWidgetRelation
217
+ - do not have any related widgets of their own (i.e. are not a source in any relation)
218
+ - are not <pk> itself
219
+ """
220
+
221
+ authentication_classes = (CsrfExemptSessionAuthentication,)
222
+ permission_classes = (QplotlyWidgetRelatedPermission,)
223
+
224
+ def get(self, request, pk, project_id):
225
+ try:
226
+ source = QplotlyWidget.objects.get(pk=pk)
227
+ except QplotlyWidget.DoesNotExist:
228
+ raise Http404
229
+
230
+ source_layers = source.layers.filter(project_id=project_id)
231
+ if not source_layers.exists():
232
+ return Response(
233
+ {'error': 'Project in URL must match source widget layers project'},
234
+ status=status.HTTP_400_BAD_REQUEST,
235
+ )
236
+
237
+ layer_ids = source_layers.values_list('pk', flat=True)
238
+
239
+ # widgets on the same layer(s), excluding source itself
240
+ candidates = QplotlyWidget.objects.filter(layers__in=layer_ids, layers__project_id=project_id).exclude(pk=pk).distinct()
241
+
242
+ # exclude widgets already targeted by any relation
243
+ targeted_pks = QplotlyWidgetRelation.objects.filter(project_id=project_id).values_list('target_id', flat=True)
244
+
245
+ # exclude widgets that are already a source in any relation
246
+ source_pks = QplotlyWidgetRelation.objects.filter(project_id=project_id).values_list('source_id', flat=True)
247
+
248
+ candidates = candidates.exclude(pk__in=targeted_pks).exclude(pk__in=source_pks)
249
+
250
+ data = [{'id': w.pk, 'title': w.title, 'type': w.type} for w in candidates]
251
+ return Response(data)
252
+
253
+
254
+ class QplotlyWidgetFreeView(APIView):
255
+ """
256
+ GET /api/widget/free/<project_id>/<layer_id>/
257
+ Returns the PKs of widgets on the given layer that are NOT a target
258
+ in any QplotlyWidgetRelation (i.e. they are not already "owned" by
259
+ another widget as a related).
260
+ These are the widgets for which the "manage related" button must be shown.
261
+ """
262
+
263
+ authentication_classes = (CsrfExemptSessionAuthentication,)
264
+ permission_classes = (QplotlyWidgetPermission,)
265
+
266
+ def get(self, request, project_id, layer_id):
267
+ try:
268
+ layer = Layer.objects.get(pk=layer_id)
269
+ except Layer.DoesNotExist:
270
+ raise Http404
271
+
272
+ if layer.project_id != project_id:
273
+ return Response(
274
+ {'error': 'Project in URL must match layer project'},
275
+ status=status.HTTP_400_BAD_REQUEST,
276
+ )
277
+
278
+ # PKs used as targets by a *different* widget (self-relations don't count)
279
+ target_pks = list(QplotlyWidgetRelation.objects.filter(
280
+ project_id=project_id,
281
+ ).exclude(
282
+ source_id=F('target_id'),
283
+ ).values_list('target_id', flat=True))
284
+
285
+ # widgets on this layer that are NOT targets of another widget
286
+ not_targets = QplotlyWidget.objects.filter(layers=layer).exclude(pk__in=target_pks)
287
+ return Response([w.pk for w in not_targets])