Export
See also
Export documentation
Models
- export.models.make_expiry_date() datetime
Creates datetime based on current time and expiry setting
- class export.models.FileExportQuerySet(model=None, query=None, using=None, hints=None)
- for_user(user: User)
filter objects by user. Implementing classes should filter down the queryset and only return objects accessible to the user. The default is to return no objects.
- pending() Self
only pending exports (waiting or in progress)
- class export.models.FileExport(*args, **kwargs)
Represents an export action triggered by user, tracks celery job and holds the exported file.
- property back_url: str | None
URL for the back button
- property task_result: AsyncResult | None
Async task result instance. Note that AsyncResult does not work with
CELERY_TASK_ALWAYS_EAGERenabled.
- run_job() AsyncResult
Triggers Celery job for this export and saves its ID
The object must be saved before triggering the job
- exception DoesNotExist
- exception MultipleObjectsReturned
Views
- class export.views.export_views.ExportView(**kwargs)
View that triggers export and redirects user to the progress view
Accepted GET parameters:
- exporter: str
Required parameter to indicate which exporter to use
- filters: str
Cache key for filters if filtering exported data
- audit_forms: int
Optional parameter to export data related to audit forms (such as observations, issues). Pass multiple form ids by repeating the argument:
?audit_forms=1&audit_forms=2
Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.
- has_permission() bool
Checks if auditor has permission for export, checks both global and form level permissions.
- get_permission_required()
Override this method to override the permission_required attribute. Must return an iterable.
- get_export_params() dict
Handles parameters passed to the view and builds a dictionary of export parameters for the exporter.
- export() FileExport
Triggers export celery job and returns Export object
- get_redirect_url(*args, **kwargs) str
Return the URL redirect to. Keyword arguments from the URL pattern match generating the redirect request are provided as kwargs to this method.
- class export.views.export_views.ExportStatusView(**kwargs)
View shows progress/status of the download and presents DOWNLOAD link when ready, or an error message
Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.
- get_context_data(**kwargs)
Insert the single object into the context dict.
- handle_htmx(request: HttpRequest, htmx: HtmxDetails, *args, **kwargs) HttpResponse
Handle HTMX request and serve response
- get_queryset()
Return the QuerySet that will be used to look up the object.
This method is called by the default implementation of get_object() and may not be called if get_object() is overridden.
Toolbar item
- class megforms.toolbar.ExportToolbarItem(label, *, exporter: type[export.exporters.base.BaseExporter], filters: str | None = None, icon='download-alt', tooltip_placement='left', params: dict | None = None, **kwargs)
Toolbar item for export options, typically placed inside a dropdown, so this wrapper places help text on the left size instead of on the bottom and uses download icon by default.
Create export option. For example:
DownloadDropdownToolbarItem([ ExportToolbarItem( gettext('Hand Hygiene Excel'), exporter=HandHygieneXlsExporter, help_text=gettext_lazy('Download hand hygiene Excel file'), filters=self.filters_key, params={ 'audit_forms': [form.pk], 'institution_slug': self.institution.slug, }, ) ])
- Parameters:
label – Display label
exporter – Exporter class to use, must be subclass of
BaseExporterfilters – Hash of the filter selection to be passed to the exporter in order to filter which items should be exported. Some exporters may not support this.
icon – icon type for the menu item
tooltip_placement – Where to position hover tooltip
params – Parameters for the exporter class. The supported parameters are specific to the selected exporter. Must be json-serializable.
Export logic
- exception export.exceptions.ExportError(message: str)
An error class with an error message for user. This is not an application error, but rather an error when user is trying to export object that is not supported by selected exporter.
- exception export.exceptions.ExportRateLimitExceeded
Raised instead of starting the export job if the user has hit the number of allowed concurrent export tasks defined in
EXPORT_RATE_LIMIT
- (celery task)export.tasks.export_file(export_uid: str)
Exports data to a file according to parameters defined in
FileExport.ExportErrorare caught and only logged to the model without failing this task. Any other errors are raised, and the job status is marked as “failed”, and subject to retry policy.- Parameters:
export_uid – UID of the
FileExportinstance
- (celery task)export.tasks.delete_expired_export_file()
Exporters
- class export.exporters.base.BaseExporter(export: FileExport)
defines base interface for exporter implementations. This class does not make any assumptions about what data is being exported
Any arguments and parameters of the export are passed to the constructor in form o
FileExportinstance. The export itself is invoked by calling a class instance without any arguments, and return value is a file object:export: FileExport = Exporter.create_export(config={'institution_id': [10]}) exporter: Exporter = Exporter() exported_file: File = exporter()
- classmethod collect_params(request: HttpRequest) dict
Builds params dictionary from request data. Sub-classes should override this method if they expect special parameters in the request.
The parameters returned by this method will be stored in
export.models.FileExport.parametersand can be accessed viaexport.exporters.base.BaseExporter.parameters.
- property parameters: dict
Export parameters
- classmethod create_export(user: User, **kwargs) FileExport
Creates
FileExportmodel instance for this exporter. Validates that user has not reached the maximum pending exports. The created instance is not saved.- Parameters:
user – The user making the export
kwargs – Keyword arguments for
FileExportmodel
- Returns:
An unsaved
FileExportwith pre-populatedexporter_clsfield and any other fields that were passed as keyword args.- Raises:
ExportRateLimitExceeded – when number of concurrent exports for this user defined by
EXPORT_RATE_LIMIThas been reached
- class export.exporters.base.ObservationExporter(export: FileExport)
Base for observation exporters. Supports exporting data from more than 1 form
Supported parameters:
audit_formsA list of
megforms.models.AuditFormids to export observations from
- classmethod collect_params(request: HttpRequest) dict
Builds params dictionary from request data. Sub-classes should override this method if they expect special parameters in the request.
The parameters returned by this method will be stored in
export.models.FileExport.parametersand can be accessed viaexport.exporters.base.BaseExporter.parameters.
- property audit_forms: AuditFormQueryset
Sanitized list of forms defined in this export’s parameters. Returned queryset includes only the forms the user can access, and excludes unpublished forms.
- Returns:
A queryset of AuditForm model
- property form_observations: Iterator[tuple[megforms.models.AuditForm, 'ObservationQueryset']]
For every audit form in the export’s scope, yields audit form and observations in that form to be exported
- class export.exporters.csv.CsvExporter(export: FileExport)
- class export.exporters.xls.XlsEnvironmentalExporter(export: FileExport)
Wraps
XlsExportexport class for environmental audits (IPC, HIQA)
- class export.exporters.xls.SimpleXlsExporter(export: FileExport)
Wraps
XlsExportSimpleinto exporter interface
- class export.exporters.xls.XlsObservationExporter(export: FileExport)
Exports observations in Excel format. Allows selection of field to be included in export.
First sheet contains data, and subsequent sheets contain data for each ward
- property fields: Iterable[CustomField | Field]
Form questions selected for this export