django-reportkit 0.1.0__tar.gz

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 (68) hide show
  1. django_reportkit-0.1.0/LICENSE +21 -0
  2. django_reportkit-0.1.0/PKG-INFO +212 -0
  3. django_reportkit-0.1.0/README.md +166 -0
  4. django_reportkit-0.1.0/pyproject.toml +56 -0
  5. django_reportkit-0.1.0/setup.cfg +4 -0
  6. django_reportkit-0.1.0/src/django_reportkit/__init__.py +10 -0
  7. django_reportkit-0.1.0/src/django_reportkit/apps.py +21 -0
  8. django_reportkit-0.1.0/src/django_reportkit/conf.py +35 -0
  9. django_reportkit-0.1.0/src/django_reportkit/errors/__init__.py +5 -0
  10. django_reportkit-0.1.0/src/django_reportkit/errors/exceptions.py +43 -0
  11. django_reportkit-0.1.0/src/django_reportkit/errors/handlers.py +37 -0
  12. django_reportkit-0.1.0/src/django_reportkit/errors/messages.py +36 -0
  13. django_reportkit-0.1.0/src/django_reportkit/exports/__init__.py +5 -0
  14. django_reportkit-0.1.0/src/django_reportkit/exports/formats.py +60 -0
  15. django_reportkit-0.1.0/src/django_reportkit/exports/policy.py +49 -0
  16. django_reportkit-0.1.0/src/django_reportkit/exports/runner.py +32 -0
  17. django_reportkit-0.1.0/src/django_reportkit/jobs/__init__.py +3 -0
  18. django_reportkit-0.1.0/src/django_reportkit/jobs/backends/__init__.py +6 -0
  19. django_reportkit-0.1.0/src/django_reportkit/jobs/backends/base.py +14 -0
  20. django_reportkit-0.1.0/src/django_reportkit/jobs/backends/celery.py +17 -0
  21. django_reportkit-0.1.0/src/django_reportkit/jobs/backends/sync.py +15 -0
  22. django_reportkit-0.1.0/src/django_reportkit/jobs/backends/thread.py +20 -0
  23. django_reportkit-0.1.0/src/django_reportkit/jobs/cleanup.py +48 -0
  24. django_reportkit-0.1.0/src/django_reportkit/jobs/models.py +89 -0
  25. django_reportkit-0.1.0/src/django_reportkit/jobs/service.py +147 -0
  26. django_reportkit-0.1.0/src/django_reportkit/jobs/storage.py +26 -0
  27. django_reportkit-0.1.0/src/django_reportkit/jobs/tasks.py +11 -0
  28. django_reportkit-0.1.0/src/django_reportkit/management/__init__.py +0 -0
  29. django_reportkit-0.1.0/src/django_reportkit/management/commands/__init__.py +0 -0
  30. django_reportkit-0.1.0/src/django_reportkit/management/commands/cleanup_report_files.py +17 -0
  31. django_reportkit-0.1.0/src/django_reportkit/migrations/0001_initial.py +44 -0
  32. django_reportkit-0.1.0/src/django_reportkit/migrations/__init__.py +0 -0
  33. django_reportkit-0.1.0/src/django_reportkit/models.py +3 -0
  34. django_reportkit-0.1.0/src/django_reportkit/reports/__init__.py +7 -0
  35. django_reportkit-0.1.0/src/django_reportkit/reports/base.py +45 -0
  36. django_reportkit-0.1.0/src/django_reportkit/reports/columns.py +28 -0
  37. django_reportkit-0.1.0/src/django_reportkit/reports/mixins/__init__.py +5 -0
  38. django_reportkit-0.1.0/src/django_reportkit/reports/mixins/access.py +58 -0
  39. django_reportkit-0.1.0/src/django_reportkit/reports/mixins/document.py +111 -0
  40. django_reportkit-0.1.0/src/django_reportkit/reports/mixins/filters.py +39 -0
  41. django_reportkit-0.1.0/src/django_reportkit/reports/model.py +76 -0
  42. django_reportkit-0.1.0/src/django_reportkit/reports/params.py +65 -0
  43. django_reportkit-0.1.0/src/django_reportkit/reports/registry.py +44 -0
  44. django_reportkit-0.1.0/src/django_reportkit/reports/rows.py +17 -0
  45. django_reportkit-0.1.0/src/django_reportkit/rest/__init__.py +3 -0
  46. django_reportkit-0.1.0/src/django_reportkit/rest/errors.py +27 -0
  47. django_reportkit-0.1.0/src/django_reportkit/rest/permissions.py +16 -0
  48. django_reportkit-0.1.0/src/django_reportkit/rest/serializers.py +147 -0
  49. django_reportkit-0.1.0/src/django_reportkit/rest/urls.py +28 -0
  50. django_reportkit-0.1.0/src/django_reportkit/rest/views.py +257 -0
  51. django_reportkit-0.1.0/src/django_reportkit/templates/django_reportkit/base.html +28 -0
  52. django_reportkit-0.1.0/src/django_reportkit/templates/django_reportkit/error.html +9 -0
  53. django_reportkit-0.1.0/src/django_reportkit/templates/django_reportkit/job.html +32 -0
  54. django_reportkit-0.1.0/src/django_reportkit/templates/django_reportkit/preview.html +35 -0
  55. django_reportkit-0.1.0/src/django_reportkit/urls.py +10 -0
  56. django_reportkit-0.1.0/src/django_reportkit/views/__init__.py +5 -0
  57. django_reportkit-0.1.0/src/django_reportkit/views/export.py +62 -0
  58. django_reportkit-0.1.0/src/django_reportkit/views/jobs.py +101 -0
  59. django_reportkit-0.1.0/src/django_reportkit/views/mixins.py +39 -0
  60. django_reportkit-0.1.0/src/django_reportkit/views/preview.py +75 -0
  61. django_reportkit-0.1.0/src/django_reportkit/views/urls.py +15 -0
  62. django_reportkit-0.1.0/src/django_reportkit.egg-info/PKG-INFO +212 -0
  63. django_reportkit-0.1.0/src/django_reportkit.egg-info/SOURCES.txt +66 -0
  64. django_reportkit-0.1.0/src/django_reportkit.egg-info/dependency_links.txt +1 -0
  65. django_reportkit-0.1.0/src/django_reportkit.egg-info/requires.txt +27 -0
  66. django_reportkit-0.1.0/src/django_reportkit.egg-info/top_level.txt +1 -0
  67. django_reportkit-0.1.0/tests/test_reports.py +228 -0
  68. django_reportkit-0.1.0/tests/test_rest.py +125 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abdullah Alaidrous
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,212 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-reportkit
3
+ Version: 0.1.0
4
+ Summary: Django reports on top of pyreportkit: model reports with filters and totals, paginated previews, and streamed or background exports to PDF, Excel and Word.
5
+ Author: Abdullah Alaidrous
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/abdalaidrous/django-reportkit
8
+ Project-URL: Repository, https://github.com/abdalaidrous/django-reportkit
9
+ Project-URL: Changelog, https://github.com/abdalaidrous/django-reportkit/blob/main/CHANGELOG.md
10
+ Keywords: django,report,reporting,pdf,excel,docx,arabic,rtl
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Framework :: Django
13
+ Classifier: Framework :: Django :: 4.2
14
+ Classifier: Framework :: Django :: 5.0
15
+ Classifier: Framework :: Django :: 5.1
16
+ Classifier: Framework :: Django :: 5.2
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Natural Language :: Arabic
19
+ Classifier: Natural Language :: English
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Topic :: Office/Business
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: Django>=4.2
26
+ Requires-Dist: pyreportkit>=0.2.0
27
+ Provides-Extra: pdf
28
+ Requires-Dist: pyreportkit[pdf]; extra == "pdf"
29
+ Provides-Extra: excel
30
+ Requires-Dist: pyreportkit[excel]; extra == "excel"
31
+ Provides-Extra: word
32
+ Requires-Dist: pyreportkit[word]; extra == "word"
33
+ Provides-Extra: celery
34
+ Requires-Dist: celery>=5.3; extra == "celery"
35
+ Provides-Extra: rest
36
+ Requires-Dist: djangorestframework>=3.14; extra == "rest"
37
+ Provides-Extra: all
38
+ Requires-Dist: pyreportkit[all]; extra == "all"
39
+ Requires-Dist: celery>=5.3; extra == "all"
40
+ Requires-Dist: djangorestframework>=3.14; extra == "all"
41
+ Provides-Extra: test
42
+ Requires-Dist: pytest>=8; extra == "test"
43
+ Requires-Dist: pytest-django>=4.8; extra == "test"
44
+ Requires-Dist: djangorestframework>=3.14; extra == "test"
45
+ Dynamic: license-file
46
+
47
+ # django-reportkit
48
+
49
+ Django reports on top of [pyreportkit](https://pypi.org/project/pyreportkit/): declare a report over a queryset, and
50
+ get a paginated HTML preview with filters, and downloads in PDF, Excel and Word that never block the request on large
51
+ data: small exports stream from a temporary file, large ones run in the background with a status page.
52
+
53
+ The data and the totals come from your database (the totals are aggregated over every filtered row, not one page);
54
+ pyreportkit only lays them out.
55
+
56
+ ## Installation
57
+
58
+ ```bash
59
+ pip install django-reportkit # HTML preview and exports
60
+ pip install "django-reportkit[all]" # + PDF, Excel, Word, Celery and Django REST Framework
61
+ pip install "django-reportkit[rest]" # only the REST API
62
+ ```
63
+
64
+ ```python
65
+ INSTALLED_APPS = [..., "django_reportkit"]
66
+ ```
67
+
68
+ ```bash
69
+ python manage.py migrate django_reportkit
70
+ ```
71
+
72
+ Requires Python 3.10+ and Django 4.2+.
73
+
74
+ ## A report
75
+
76
+ ```python
77
+ from django import forms
78
+ from django_reportkit import Column, ModelReport, Sum
79
+
80
+
81
+ class MovementFilterForm(forms.Form):
82
+ date_from = forms.DateField(required=False)
83
+ account = forms.CharField(required=False)
84
+
85
+
86
+ class MovementReport(ModelReport):
87
+ title = "تقرير الحركة المالية"
88
+ model = Movement
89
+ filter_form = MovementFilterForm
90
+ filter_lookups = {"date_from": "date__gte", "account": "account__name"}
91
+ formats = ("pdf", "xlsx", "xlsx-data", "docx")
92
+ paginate_by = 50
93
+ permission_required = "ledger.view_movement"
94
+ columns = (
95
+ Column("voucher", "رقم السند", align="center"),
96
+ Column("date", "التاريخ", format="date", date_format="%d/%m/%Y"),
97
+ Column("account__name", "الحساب"),
98
+ Column("amount", "المبلغ", format="currency", currency="﷼"),
99
+ )
100
+ totals = {"amount": Sum("amount")}
101
+
102
+ def get_queryset(self):
103
+ return super().get_queryset().filter(company=self.user.company).order_by("date")
104
+
105
+ def build(self, builder, table): # optional: anything ReportBuilder offers
106
+ return builder.header(hotel_identity(), repeat=True).add(table).qr_code(self.verification_url()).page_number()
107
+ ```
108
+
109
+ ```python
110
+ # urls.py
111
+ urlpatterns = [
112
+ path("reports/movements/", include(MovementReport.urls())), # preview and exports
113
+ path("reports/", include("django_reportkit.urls")), # background job status and downloads
114
+ ]
115
+ ```
116
+
117
+ | URL | Name | What it does |
118
+ |---|---|---|
119
+ | `reports/movements/` | `movement-report-preview` | One page of rows (`?page=`), the filter form and download links; totals of every row. |
120
+ | `reports/movements/export/<format>/` | `movement-report-export` | Downloads the filtered report, or starts a background job when it is large. |
121
+ | `reports/jobs/<id>/` | `django_reportkit:job` | The job's progress (`?format=json` for polling) and its download link. |
122
+ | `reports/jobs/<id>/download/` | `django_reportkit:download` | The stored file, for the job's user. |
123
+
124
+ Reports require a logged-in user: anonymous visitors are sent to `LOGIN_URL`. Set `login_required = False` for a
125
+ public report; its background exports still ask for a login, since a job belongs to the user who started it and only
126
+ that user (or staff) can follow and download it. `permission_required` adds Django permissions on top.
127
+
128
+ Columns read `values()` fields, so related fields (`account__name`) and annotations work, and rows stream with
129
+ `iterator()`. Columns take every pyreportkit `TableColumn` option. `Report` (without a model) is the base class for
130
+ reports whose rows come from somewhere else: implement `get_rows()`, `count()`, `get_page()` and optionally
131
+ `get_totals()`.
132
+
133
+ ## REST API (Django REST Framework)
134
+
135
+ Register the reports once and include one set of URLs that serves all of them by slug (for a generic report
136
+ viewer):
137
+
138
+ ```python
139
+ # ledger/reports.py (every installed app's reports.py is imported at startup)
140
+ from django_reportkit import ModelReport, register
141
+
142
+ @register
143
+ class MovementReport(ModelReport): # slug "movement-report"; set slug = "..." to choose it
144
+ ...
145
+
146
+ # urls.py
147
+ urlpatterns = [path("api/reports/", include("django_reportkit.rest.urls"))]
148
+ ```
149
+
150
+ | Request | Response |
151
+ |---|---|
152
+ | `GET api/reports/` | The registered reports the user may open: `[{"slug", "title", "formats", "preview_url", "html_url"}]`. |
153
+ | `GET api/reports/<slug>/?page=2&...` | JSON page (below). |
154
+ | `GET api/reports/<slug>/html/?page=2&...` | One page as a complete HTML document laid out like the PDF; `X-Report-Page`, `X-Report-Pages` and `X-Report-Count` headers (list them in `CORS_EXPOSE_HEADERS` for another origin). |
155
+ | `GET api/reports/<slug>/export/<format>/?...` | The file, or `202` with a background job. |
156
+
157
+ A single report can also get its own URLs: `path("api/movements/", include(MovementReport.api_urls()))`.
158
+
159
+ Authentication is whatever `REST_FRAMEWORK` configures (session, token, JWT...); the report's `login_required` and
160
+ `permission_required` still apply. `api_urls(authentication_classes=[...], throttle_classes=[...])` passes options to
161
+ the views.
162
+
163
+ | Request | Response |
164
+ |---|---|
165
+ | `GET api/reports/movement-report/?page=2&date_from=2026-11-01` | `{"count", "page", "pages", "next", "previous", "columns", "results", "totals", "filters", "downloads"}`; totals cover every filtered row. Invalid filters: `400 {"detail", "code": "report_filter", "errors": {...}}`. |
166
+ | `GET api/reports/movement-report/export/xlsx/?...` | The file for a small report; `202 Accepted` with the job (and `Location: status_url`) for a large one; `413` with `"code": "export_too_large"` above `MAX_ROWS`. |
167
+ | `GET api/reports/jobs/<id>/` | `{"id", "status", "label", "finished", "error", "rows", "status_url", "download_url", ...}`: poll until `finished`. |
168
+ | `GET api/reports/jobs/<id>/download/` | The stored file, for the job's user. |
169
+
170
+ Every error is JSON with a friendly `detail` and a stable `code`; the traceback only goes to the logs.
171
+
172
+ ## How exports are delivered
173
+
174
+ `ExportPolicy` decides from the row count:
175
+
176
+ - up to `DIRECT_LIMITS[format]`: written to a temporary file and streamed with `FileResponse`;
177
+ - up to `MAX_ROWS[format]`: a `ReportJob` runs in the background, the user goes to its status page, and the file is kept
178
+ in storage for `JOB_TTL_HOURS`;
179
+ - above it: a friendly refusal that suggests "Excel (data)" (streamed, no row limit) or narrower filters.
180
+
181
+ Errors are logged with their traceback; users see a short message (filters, size, unavailable format, or a generic
182
+ failure), never a server error page.
183
+
184
+ ## Settings
185
+
186
+ ```python
187
+ REPORTKIT = {
188
+ "PAGINATE_BY": 50,
189
+ "DIRECT_LIMITS": {"pdf": 2000, "docx": 2000, "xlsx": 20000, "xlsx-data": 100000, "html": 5000},
190
+ "MAX_ROWS": {"pdf": 50000, "docx": 50000, "xlsx": 100000, "xlsx-data": None, "html": 20000},
191
+ "JOB_BACKEND": "django_reportkit.jobs.backends.ThreadBackend", # or SyncBackend, CeleryBackend
192
+ "JOB_STORAGE": "default", # a key of settings.STORAGES
193
+ "JOB_DIRECTORY": "reports",
194
+ "JOB_TTL_HOURS": 24,
195
+ "STATUS_POLL_SECONDS": 3,
196
+ "PDF_WORKERS": 1, # pyreportkit parallel PDF layout
197
+ }
198
+ ```
199
+
200
+ - `ThreadBackend` (default) needs nothing else but loses a job if the process restarts; use `CeleryBackend` in
201
+ production (`pip install "django-reportkit[celery]"`, task `django_reportkit.run_report_job`).
202
+ - Run `python manage.py cleanup_report_files` periodically to delete expired files.
203
+ - Override the templates in `django_reportkit/` (`base.html`, `preview.html`, `job.html`, `error.html`) to match your site.
204
+
205
+ ## Development
206
+
207
+ Tests run with pytest-django (`tests/` has a small app and settings):
208
+
209
+ ```bash
210
+ pip install -e ".[all,test]"
211
+ python -m pytest
212
+ ```
@@ -0,0 +1,166 @@
1
+ # django-reportkit
2
+
3
+ Django reports on top of [pyreportkit](https://pypi.org/project/pyreportkit/): declare a report over a queryset, and
4
+ get a paginated HTML preview with filters, and downloads in PDF, Excel and Word that never block the request on large
5
+ data: small exports stream from a temporary file, large ones run in the background with a status page.
6
+
7
+ The data and the totals come from your database (the totals are aggregated over every filtered row, not one page);
8
+ pyreportkit only lays them out.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ pip install django-reportkit # HTML preview and exports
14
+ pip install "django-reportkit[all]" # + PDF, Excel, Word, Celery and Django REST Framework
15
+ pip install "django-reportkit[rest]" # only the REST API
16
+ ```
17
+
18
+ ```python
19
+ INSTALLED_APPS = [..., "django_reportkit"]
20
+ ```
21
+
22
+ ```bash
23
+ python manage.py migrate django_reportkit
24
+ ```
25
+
26
+ Requires Python 3.10+ and Django 4.2+.
27
+
28
+ ## A report
29
+
30
+ ```python
31
+ from django import forms
32
+ from django_reportkit import Column, ModelReport, Sum
33
+
34
+
35
+ class MovementFilterForm(forms.Form):
36
+ date_from = forms.DateField(required=False)
37
+ account = forms.CharField(required=False)
38
+
39
+
40
+ class MovementReport(ModelReport):
41
+ title = "تقرير الحركة المالية"
42
+ model = Movement
43
+ filter_form = MovementFilterForm
44
+ filter_lookups = {"date_from": "date__gte", "account": "account__name"}
45
+ formats = ("pdf", "xlsx", "xlsx-data", "docx")
46
+ paginate_by = 50
47
+ permission_required = "ledger.view_movement"
48
+ columns = (
49
+ Column("voucher", "رقم السند", align="center"),
50
+ Column("date", "التاريخ", format="date", date_format="%d/%m/%Y"),
51
+ Column("account__name", "الحساب"),
52
+ Column("amount", "المبلغ", format="currency", currency="﷼"),
53
+ )
54
+ totals = {"amount": Sum("amount")}
55
+
56
+ def get_queryset(self):
57
+ return super().get_queryset().filter(company=self.user.company).order_by("date")
58
+
59
+ def build(self, builder, table): # optional: anything ReportBuilder offers
60
+ return builder.header(hotel_identity(), repeat=True).add(table).qr_code(self.verification_url()).page_number()
61
+ ```
62
+
63
+ ```python
64
+ # urls.py
65
+ urlpatterns = [
66
+ path("reports/movements/", include(MovementReport.urls())), # preview and exports
67
+ path("reports/", include("django_reportkit.urls")), # background job status and downloads
68
+ ]
69
+ ```
70
+
71
+ | URL | Name | What it does |
72
+ |---|---|---|
73
+ | `reports/movements/` | `movement-report-preview` | One page of rows (`?page=`), the filter form and download links; totals of every row. |
74
+ | `reports/movements/export/<format>/` | `movement-report-export` | Downloads the filtered report, or starts a background job when it is large. |
75
+ | `reports/jobs/<id>/` | `django_reportkit:job` | The job's progress (`?format=json` for polling) and its download link. |
76
+ | `reports/jobs/<id>/download/` | `django_reportkit:download` | The stored file, for the job's user. |
77
+
78
+ Reports require a logged-in user: anonymous visitors are sent to `LOGIN_URL`. Set `login_required = False` for a
79
+ public report; its background exports still ask for a login, since a job belongs to the user who started it and only
80
+ that user (or staff) can follow and download it. `permission_required` adds Django permissions on top.
81
+
82
+ Columns read `values()` fields, so related fields (`account__name`) and annotations work, and rows stream with
83
+ `iterator()`. Columns take every pyreportkit `TableColumn` option. `Report` (without a model) is the base class for
84
+ reports whose rows come from somewhere else: implement `get_rows()`, `count()`, `get_page()` and optionally
85
+ `get_totals()`.
86
+
87
+ ## REST API (Django REST Framework)
88
+
89
+ Register the reports once and include one set of URLs that serves all of them by slug (for a generic report
90
+ viewer):
91
+
92
+ ```python
93
+ # ledger/reports.py (every installed app's reports.py is imported at startup)
94
+ from django_reportkit import ModelReport, register
95
+
96
+ @register
97
+ class MovementReport(ModelReport): # slug "movement-report"; set slug = "..." to choose it
98
+ ...
99
+
100
+ # urls.py
101
+ urlpatterns = [path("api/reports/", include("django_reportkit.rest.urls"))]
102
+ ```
103
+
104
+ | Request | Response |
105
+ |---|---|
106
+ | `GET api/reports/` | The registered reports the user may open: `[{"slug", "title", "formats", "preview_url", "html_url"}]`. |
107
+ | `GET api/reports/<slug>/?page=2&...` | JSON page (below). |
108
+ | `GET api/reports/<slug>/html/?page=2&...` | One page as a complete HTML document laid out like the PDF; `X-Report-Page`, `X-Report-Pages` and `X-Report-Count` headers (list them in `CORS_EXPOSE_HEADERS` for another origin). |
109
+ | `GET api/reports/<slug>/export/<format>/?...` | The file, or `202` with a background job. |
110
+
111
+ A single report can also get its own URLs: `path("api/movements/", include(MovementReport.api_urls()))`.
112
+
113
+ Authentication is whatever `REST_FRAMEWORK` configures (session, token, JWT...); the report's `login_required` and
114
+ `permission_required` still apply. `api_urls(authentication_classes=[...], throttle_classes=[...])` passes options to
115
+ the views.
116
+
117
+ | Request | Response |
118
+ |---|---|
119
+ | `GET api/reports/movement-report/?page=2&date_from=2026-11-01` | `{"count", "page", "pages", "next", "previous", "columns", "results", "totals", "filters", "downloads"}`; totals cover every filtered row. Invalid filters: `400 {"detail", "code": "report_filter", "errors": {...}}`. |
120
+ | `GET api/reports/movement-report/export/xlsx/?...` | The file for a small report; `202 Accepted` with the job (and `Location: status_url`) for a large one; `413` with `"code": "export_too_large"` above `MAX_ROWS`. |
121
+ | `GET api/reports/jobs/<id>/` | `{"id", "status", "label", "finished", "error", "rows", "status_url", "download_url", ...}`: poll until `finished`. |
122
+ | `GET api/reports/jobs/<id>/download/` | The stored file, for the job's user. |
123
+
124
+ Every error is JSON with a friendly `detail` and a stable `code`; the traceback only goes to the logs.
125
+
126
+ ## How exports are delivered
127
+
128
+ `ExportPolicy` decides from the row count:
129
+
130
+ - up to `DIRECT_LIMITS[format]`: written to a temporary file and streamed with `FileResponse`;
131
+ - up to `MAX_ROWS[format]`: a `ReportJob` runs in the background, the user goes to its status page, and the file is kept
132
+ in storage for `JOB_TTL_HOURS`;
133
+ - above it: a friendly refusal that suggests "Excel (data)" (streamed, no row limit) or narrower filters.
134
+
135
+ Errors are logged with their traceback; users see a short message (filters, size, unavailable format, or a generic
136
+ failure), never a server error page.
137
+
138
+ ## Settings
139
+
140
+ ```python
141
+ REPORTKIT = {
142
+ "PAGINATE_BY": 50,
143
+ "DIRECT_LIMITS": {"pdf": 2000, "docx": 2000, "xlsx": 20000, "xlsx-data": 100000, "html": 5000},
144
+ "MAX_ROWS": {"pdf": 50000, "docx": 50000, "xlsx": 100000, "xlsx-data": None, "html": 20000},
145
+ "JOB_BACKEND": "django_reportkit.jobs.backends.ThreadBackend", # or SyncBackend, CeleryBackend
146
+ "JOB_STORAGE": "default", # a key of settings.STORAGES
147
+ "JOB_DIRECTORY": "reports",
148
+ "JOB_TTL_HOURS": 24,
149
+ "STATUS_POLL_SECONDS": 3,
150
+ "PDF_WORKERS": 1, # pyreportkit parallel PDF layout
151
+ }
152
+ ```
153
+
154
+ - `ThreadBackend` (default) needs nothing else but loses a job if the process restarts; use `CeleryBackend` in
155
+ production (`pip install "django-reportkit[celery]"`, task `django_reportkit.run_report_job`).
156
+ - Run `python manage.py cleanup_report_files` periodically to delete expired files.
157
+ - Override the templates in `django_reportkit/` (`base.html`, `preview.html`, `job.html`, `error.html`) to match your site.
158
+
159
+ ## Development
160
+
161
+ Tests run with pytest-django (`tests/` has a small app and settings):
162
+
163
+ ```bash
164
+ pip install -e ".[all,test]"
165
+ python -m pytest
166
+ ```
@@ -0,0 +1,56 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ # The distribution is "django-reportkit"; the import name is "django_reportkit".
7
+ name = "django-reportkit"
8
+ version = "0.1.0"
9
+ description = "Django reports on top of pyreportkit: model reports with filters and totals, paginated previews, and streamed or background exports to PDF, Excel and Word."
10
+ readme = "README.md"
11
+ requires-python = ">=3.10"
12
+ license = "MIT"
13
+ license-files = ["LICENSE"]
14
+ authors = [{ name = "Abdullah Alaidrous" }]
15
+ keywords = ["django", "report", "reporting", "pdf", "excel", "docx", "arabic", "rtl"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Framework :: Django",
19
+ "Framework :: Django :: 4.2",
20
+ "Framework :: Django :: 5.0",
21
+ "Framework :: Django :: 5.1",
22
+ "Framework :: Django :: 5.2",
23
+ "Intended Audience :: Developers",
24
+ "Natural Language :: Arabic",
25
+ "Natural Language :: English",
26
+ "Programming Language :: Python :: 3",
27
+ "Topic :: Office/Business",
28
+ ]
29
+ dependencies = [
30
+ "Django>=4.2",
31
+ "pyreportkit>=0.2.0", # ReportBuilder, export_to, QRCode and Chart arrive after 0.1.0.
32
+ ]
33
+
34
+ [project.optional-dependencies]
35
+ pdf = ["pyreportkit[pdf]"]
36
+ excel = ["pyreportkit[excel]"]
37
+ word = ["pyreportkit[word]"]
38
+ celery = ["celery>=5.3"]
39
+ rest = ["djangorestframework>=3.14"]
40
+ all = ["pyreportkit[all]", "celery>=5.3", "djangorestframework>=3.14"]
41
+ test = ["pytest>=8", "pytest-django>=4.8", "djangorestframework>=3.14"]
42
+
43
+ [project.urls]
44
+ Homepage = "https://github.com/abdalaidrous/django-reportkit"
45
+ Repository = "https://github.com/abdalaidrous/django-reportkit"
46
+ Changelog = "https://github.com/abdalaidrous/django-reportkit/blob/main/CHANGELOG.md"
47
+
48
+ [tool.setuptools.packages.find]
49
+ where = ["src"]
50
+
51
+ [tool.setuptools.package-data]
52
+ django_reportkit = ["templates/**/*", "locale/**/*"]
53
+
54
+ [tool.pytest.ini_options]
55
+ DJANGO_SETTINGS_MODULE = "tests.settings"
56
+ pythonpath = [".", "src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,10 @@
1
+ """
2
+ Django reports on top of pyreportkit.
3
+ """
4
+
5
+ from django.db.models import Avg, Count, Max, Min, Sum
6
+
7
+ from .reports import Column, ModelReport, Report, ReportParams, register
8
+
9
+ __version__ = "0.1.0"
10
+ __all__ = ["Avg", "Column", "Count", "Max", "Min", "ModelReport", "Report", "ReportParams", "Sum", "register"]
@@ -0,0 +1,21 @@
1
+ from django.apps import AppConfig
2
+ from django.utils.translation import gettext_lazy as _
3
+
4
+
5
+ class ReportKitConfig(AppConfig):
6
+ """
7
+ Django application for pyreportkit reports: templates, the ReportJob model and its cleanup command.
8
+ """
9
+
10
+ name = "django_reportkit"
11
+ label = "django_reportkit"
12
+ verbose_name = _("Reports")
13
+ default_auto_field = "django.db.models.BigAutoField"
14
+
15
+ def ready(self):
16
+ """
17
+ Import every installed app's reports module, so reports registered with @register are known at startup.
18
+ """
19
+ from django.utils.module_loading import autodiscover_modules
20
+
21
+ autodiscover_modules("reports")
@@ -0,0 +1,35 @@
1
+ from django.conf import settings
2
+
3
+ DEFAULTS = {
4
+ "PAGINATE_BY": 50,
5
+ # Rows above which a format is generated in the background instead of during the request; None never moves it.
6
+ "DIRECT_LIMITS": {"pdf": 2000, "docx": 2000, "xlsx": 20000, "xlsx-data": 100000, "html": 5000},
7
+ # Rows above which a format is refused with a suggestion to use another one; None has no limit.
8
+ "MAX_ROWS": {"pdf": 50000, "docx": 50000, "xlsx": 100000, "xlsx-data": None, "html": 20000},
9
+ "JOB_BACKEND": "django_reportkit.jobs.backends.ThreadBackend",
10
+ "JOB_STORAGE": "default", # A key of settings.STORAGES.
11
+ "JOB_DIRECTORY": "reports",
12
+ "JOB_TTL_HOURS": 24,
13
+ "STATUS_POLL_SECONDS": 3,
14
+ "PDF_WORKERS": 1,
15
+ }
16
+
17
+
18
+ class ReportKitSettings:
19
+ """
20
+ Read settings.REPORTKIT over the defaults on every access, so overridden settings (as in tests) apply at once.
21
+ """
22
+
23
+ def __getattr__(self, name):
24
+ """
25
+ Return one setting; dictionaries are merged key by key over their defaults.
26
+ """
27
+ if name not in DEFAULTS:
28
+ raise AttributeError(f"Unknown django-reportkit setting: {name}")
29
+ configured = getattr(settings, "REPORTKIT", {}).get(name, DEFAULTS[name])
30
+ if isinstance(DEFAULTS[name], dict):
31
+ return {**DEFAULTS[name], **configured}
32
+ return configured
33
+
34
+
35
+ reportkit_settings = ReportKitSettings()
@@ -0,0 +1,5 @@
1
+ from .exceptions import ExportTooLargeError, ReportError, ReportFilterError, UnknownFormatError
2
+ from .handlers import error_response, log_error
3
+ from .messages import friendly_message
4
+
5
+ __all__ = ["ExportTooLargeError", "ReportError", "ReportFilterError", "UnknownFormatError", "error_response", "friendly_message", "log_error"]
@@ -0,0 +1,43 @@
1
+ class ReportError(Exception):
2
+ """
3
+ Base class of the errors django-reportkit shows to users with a friendly message.
4
+ """
5
+
6
+
7
+ class ReportFilterError(ReportError):
8
+ """
9
+ The filter form is invalid; errors holds the form errors.
10
+ """
11
+
12
+ def __init__(self, errors):
13
+ """
14
+ Keep the form errors.
15
+ """
16
+ super().__init__("The report filters are invalid.")
17
+ self.errors = errors
18
+
19
+
20
+ class UnknownFormatError(ReportError):
21
+ """
22
+ The requested export format is not offered by the report.
23
+ """
24
+
25
+ def __init__(self, format):
26
+ """
27
+ Keep the format name.
28
+ """
29
+ super().__init__(f"Unknown or disabled export format: {format}")
30
+ self.format = format
31
+
32
+
33
+ class ExportTooLargeError(ReportError):
34
+ """
35
+ The report has more rows than the format allows; alternative names a format that can hold it, if any.
36
+ """
37
+
38
+ def __init__(self, format, rows, limit, alternative=None):
39
+ """
40
+ Keep the numbers needed to explain the refusal.
41
+ """
42
+ super().__init__(f"{rows} rows exceed the {format} limit of {limit}.")
43
+ self.format, self.rows, self.limit, self.alternative = format, rows, limit, alternative
@@ -0,0 +1,37 @@
1
+ import logging
2
+
3
+ from django.shortcuts import render
4
+ from django.utils.http import url_has_allowed_host_and_scheme
5
+
6
+ from .exceptions import ReportError
7
+ from .messages import friendly_message, status_code
8
+
9
+ logger = logging.getLogger("django_reportkit")
10
+
11
+
12
+ def log_error(error, report=None):
13
+ """
14
+ Log an error: expected report errors as warnings, anything else with its traceback.
15
+ """
16
+ name = type(report).__name__ if report is not None else "report"
17
+ if isinstance(error, ReportError):
18
+ logger.warning("%s: %s", name, error)
19
+ else:
20
+ logger.exception("%s failed", name, exc_info=error)
21
+
22
+
23
+ def error_response(request, error, report=None):
24
+ """
25
+ Log the error and render the friendly error page with the matching status.
26
+ """
27
+ log_error(error, report)
28
+ context = {"message": friendly_message(error), "report": report, "back_url": back_url(request)}
29
+ return render(request, "django_reportkit/error.html", context, status=status_code(error))
30
+
31
+
32
+ def back_url(request):
33
+ """
34
+ Return the referring page when it belongs to this site, for the error page's back link.
35
+ """
36
+ referer = request.META.get("HTTP_REFERER")
37
+ return referer if referer and url_has_allowed_host_and_scheme(referer, allowed_hosts={request.get_host()}, require_https=request.is_secure()) else None
@@ -0,0 +1,36 @@
1
+ from django.utils.translation import gettext as _
2
+
3
+ from .exceptions import ExportTooLargeError, ReportFilterError, UnknownFormatError
4
+
5
+
6
+ def friendly_message(error):
7
+ """
8
+ Return the message a user sees for an error; technical details stay in the logs.
9
+ """
10
+ if isinstance(error, ReportFilterError):
11
+ return _("Please correct the report filters.")
12
+ if isinstance(error, UnknownFormatError):
13
+ return _("This report cannot be downloaded in that format.")
14
+ if isinstance(error, ExportTooLargeError):
15
+ message = _("The report has %(rows)s rows, more than %(limit)s allowed for this format.") % {"rows": f"{error.rows:,}", "limit": f"{error.limit:,}"}
16
+ if error.alternative:
17
+ message += " " + _("Download it as Excel (data) instead, or narrow the filters.")
18
+ else:
19
+ message += " " + _("Narrow the filters and try again.")
20
+ return message
21
+ if isinstance(error, ImportError):
22
+ return _("This format is not available on the server right now.")
23
+ return _("The report could not be created. Please try again later.")
24
+
25
+
26
+ def status_code(error):
27
+ """
28
+ Return the HTTP status that matches the error.
29
+ """
30
+ if isinstance(error, (ReportFilterError, UnknownFormatError)):
31
+ return 400
32
+ if isinstance(error, ExportTooLargeError):
33
+ return 413
34
+ if isinstance(error, ImportError):
35
+ return 503
36
+ return 500
@@ -0,0 +1,5 @@
1
+ from .formats import FORMATS, ExportFormat, get_format
2
+ from .policy import Delivery, ExportPolicy
3
+ from .runner import ExportRunner
4
+
5
+ __all__ = ["Delivery", "ExportFormat", "ExportPolicy", "ExportRunner", "FORMATS", "get_format"]