2022-11-10 08:01:52 -08:00
|
|
|
import csv
|
2020-08-11 15:09:23 -04:00
|
|
|
import json
|
|
|
|
import re
|
2022-11-10 08:01:52 -08:00
|
|
|
from io import StringIO
|
2020-08-11 15:09:23 -04:00
|
|
|
|
|
|
|
import yaml
|
|
|
|
from django import forms
|
2022-11-10 08:01:52 -08:00
|
|
|
from utilities.forms.utils import parse_csv
|
2020-08-11 15:09:23 -04:00
|
|
|
|
2022-11-10 08:01:52 -08:00
|
|
|
from .choices import ImportFormatChoices
|
2021-09-02 16:48:54 -04:00
|
|
|
from .widgets import APISelect, APISelectMultiple, ClearableFileInput, StaticSelect
|
2021-03-13 02:27:32 -07:00
|
|
|
|
2020-08-11 15:09:23 -04:00
|
|
|
__all__ = (
|
|
|
|
'BootstrapMixin',
|
|
|
|
'BulkEditForm',
|
|
|
|
'BulkRenameForm',
|
|
|
|
'ConfirmationForm',
|
|
|
|
'CSVModelForm',
|
2021-11-19 15:12:45 -05:00
|
|
|
'FilterForm',
|
2020-08-11 15:09:23 -04:00
|
|
|
'ImportForm',
|
|
|
|
'ReturnURLForm',
|
|
|
|
'TableConfigForm',
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2022-01-28 16:47:54 -05:00
|
|
|
#
|
|
|
|
# Mixins
|
|
|
|
#
|
|
|
|
|
2021-11-18 16:19:25 -05:00
|
|
|
class BootstrapMixin:
|
2020-08-11 15:09:23 -04:00
|
|
|
"""
|
|
|
|
Add the base Bootstrap CSS classes to form elements.
|
|
|
|
"""
|
2021-05-25 08:26:36 -07:00
|
|
|
|
2020-08-11 15:09:23 -04:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
exempt_widgets = [
|
|
|
|
forms.CheckboxInput,
|
|
|
|
forms.FileInput,
|
2021-03-13 02:27:32 -07:00
|
|
|
forms.RadioSelect,
|
2021-05-25 08:26:36 -07:00
|
|
|
forms.Select,
|
2021-03-13 02:27:32 -07:00
|
|
|
APISelect,
|
|
|
|
APISelectMultiple,
|
2021-09-02 16:48:54 -04:00
|
|
|
ClearableFileInput,
|
2021-07-17 21:24:20 -07:00
|
|
|
StaticSelect,
|
2020-08-11 15:09:23 -04:00
|
|
|
]
|
|
|
|
|
|
|
|
for field_name, field in self.fields.items():
|
2021-03-13 02:27:32 -07:00
|
|
|
|
2020-08-11 15:09:23 -04:00
|
|
|
if field.widget.__class__ not in exempt_widgets:
|
|
|
|
css = field.widget.attrs.get('class', '')
|
|
|
|
field.widget.attrs['class'] = ' '.join([css, 'form-control']).strip()
|
2021-03-13 02:27:32 -07:00
|
|
|
|
2020-08-11 15:09:23 -04:00
|
|
|
if field.required and not isinstance(field.widget, forms.FileInput):
|
|
|
|
field.widget.attrs['required'] = 'required'
|
2021-03-13 02:27:32 -07:00
|
|
|
|
|
|
|
if 'placeholder' not in field.widget.attrs and field.label is not None:
|
2020-08-11 15:09:23 -04:00
|
|
|
field.widget.attrs['placeholder'] = field.label
|
|
|
|
|
2021-03-13 02:27:32 -07:00
|
|
|
if field.widget.__class__ == forms.CheckboxInput:
|
|
|
|
css = field.widget.attrs.get('class', '')
|
|
|
|
field.widget.attrs['class'] = ' '.join((css, 'form-check-input')).strip()
|
|
|
|
|
2021-05-25 08:26:36 -07:00
|
|
|
if field.widget.__class__ == forms.Select:
|
|
|
|
css = field.widget.attrs.get('class', '')
|
|
|
|
field.widget.attrs['class'] = ' '.join((css, 'form-select')).strip()
|
|
|
|
|
2020-08-11 15:09:23 -04:00
|
|
|
|
2022-01-28 16:47:54 -05:00
|
|
|
#
|
|
|
|
# Form classes
|
|
|
|
#
|
|
|
|
|
2020-08-11 15:09:23 -04:00
|
|
|
class ReturnURLForm(forms.Form):
|
|
|
|
"""
|
|
|
|
Provides a hidden return URL field to control where the user is directed after the form is submitted.
|
|
|
|
"""
|
|
|
|
return_url = forms.CharField(required=False, widget=forms.HiddenInput())
|
|
|
|
|
|
|
|
|
|
|
|
class ConfirmationForm(BootstrapMixin, ReturnURLForm):
|
|
|
|
"""
|
|
|
|
A generic confirmation form. The form is not valid unless the confirm field is checked.
|
|
|
|
"""
|
|
|
|
confirm = forms.BooleanField(required=True, widget=forms.HiddenInput(), initial=True)
|
|
|
|
|
|
|
|
|
2022-02-01 11:00:18 -05:00
|
|
|
class BulkEditForm(BootstrapMixin, forms.Form):
|
|
|
|
"""
|
|
|
|
Provides bulk edit support for objects.
|
|
|
|
"""
|
|
|
|
nullable_fields = ()
|
2022-01-17 11:12:54 -05:00
|
|
|
|
|
|
|
|
2021-04-18 11:36:12 -07:00
|
|
|
class BulkRenameForm(BootstrapMixin, forms.Form):
|
2020-08-11 15:09:23 -04:00
|
|
|
"""
|
|
|
|
An extendable form to be used for renaming objects in bulk.
|
|
|
|
"""
|
|
|
|
find = forms.CharField()
|
2022-03-04 13:30:32 -05:00
|
|
|
replace = forms.CharField(
|
|
|
|
required=False
|
|
|
|
)
|
2020-08-11 15:09:23 -04:00
|
|
|
use_regex = forms.BooleanField(
|
|
|
|
required=False,
|
|
|
|
initial=True,
|
|
|
|
label='Use regular expressions'
|
|
|
|
)
|
|
|
|
|
|
|
|
def clean(self):
|
2020-12-28 12:54:42 -05:00
|
|
|
super().clean()
|
2020-08-11 15:09:23 -04:00
|
|
|
|
|
|
|
# Validate regular expression in "find" field
|
|
|
|
if self.cleaned_data['use_regex']:
|
|
|
|
try:
|
|
|
|
re.compile(self.cleaned_data['find'])
|
|
|
|
except re.error:
|
|
|
|
raise forms.ValidationError({
|
|
|
|
'find': "Invalid regular expression"
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
class CSVModelForm(forms.ModelForm):
|
|
|
|
"""
|
|
|
|
ModelForm used for the import of objects in CSV format.
|
|
|
|
"""
|
2022-11-10 08:01:52 -08:00
|
|
|
def __init__(self, *args, headers=None, fields=None, **kwargs):
|
|
|
|
headers = headers or {}
|
|
|
|
fields = fields or []
|
2020-08-11 15:09:23 -04:00
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
# Modify the model form to accommodate any customized to_field_name properties
|
2022-11-10 08:01:52 -08:00
|
|
|
for field, to_field in headers.items():
|
|
|
|
if to_field is not None:
|
|
|
|
self.fields[field].to_field_name = to_field
|
|
|
|
|
|
|
|
# Omit any fields not specified (e.g. because the form is being used to
|
|
|
|
# updated rather than create objects)
|
|
|
|
if fields:
|
|
|
|
for field in list(self.fields.keys()):
|
|
|
|
if field not in fields:
|
|
|
|
del self.fields[field]
|
2020-08-11 15:09:23 -04:00
|
|
|
|
|
|
|
|
|
|
|
class ImportForm(BootstrapMixin, forms.Form):
|
|
|
|
data = forms.CharField(
|
2022-11-10 08:01:52 -08:00
|
|
|
required=False,
|
2022-08-10 16:08:52 -04:00
|
|
|
widget=forms.Textarea(attrs={'class': 'font-monospace'}),
|
2022-11-10 08:01:52 -08:00
|
|
|
help_text="Enter object data in CSV, JSON or YAML format."
|
|
|
|
)
|
|
|
|
data_file = forms.FileField(
|
|
|
|
label="Data file",
|
|
|
|
required=False
|
2020-08-11 15:09:23 -04:00
|
|
|
)
|
2022-11-10 08:01:52 -08:00
|
|
|
# TODO: Enable auto-detection of format
|
2020-08-11 15:09:23 -04:00
|
|
|
format = forms.ChoiceField(
|
2022-11-10 08:01:52 -08:00
|
|
|
choices=ImportFormatChoices,
|
|
|
|
initial=ImportFormatChoices.CSV,
|
|
|
|
widget=StaticSelect()
|
2020-08-11 15:09:23 -04:00
|
|
|
)
|
|
|
|
|
2022-11-10 08:01:52 -08:00
|
|
|
data_field = 'data'
|
|
|
|
|
2020-08-11 15:09:23 -04:00
|
|
|
def clean(self):
|
2020-12-28 12:54:42 -05:00
|
|
|
super().clean()
|
2020-08-11 15:09:23 -04:00
|
|
|
format = self.cleaned_data['format']
|
|
|
|
|
2022-11-10 08:01:52 -08:00
|
|
|
# Determine whether we're reading from form data or an uploaded file
|
|
|
|
if self.cleaned_data['data'] and self.cleaned_data['data_file']:
|
|
|
|
raise forms.ValidationError("Form data must be empty when uploading a file.")
|
|
|
|
if 'data_file' in self.files:
|
|
|
|
self.data_field = 'data_file'
|
|
|
|
file = self.files.get('data_file')
|
|
|
|
data = file.read().decode('utf-8')
|
2020-08-11 15:09:23 -04:00
|
|
|
else:
|
2022-11-10 08:01:52 -08:00
|
|
|
data = self.cleaned_data['data']
|
|
|
|
|
|
|
|
# Process data according to the selected format
|
|
|
|
if format == ImportFormatChoices.CSV:
|
|
|
|
self.cleaned_data['data'] = self._clean_csv(data)
|
|
|
|
elif format == ImportFormatChoices.JSON:
|
|
|
|
self.cleaned_data['data'] = self._clean_json(data)
|
|
|
|
elif format == ImportFormatChoices.YAML:
|
|
|
|
self.cleaned_data['data'] = self._clean_yaml(data)
|
|
|
|
|
|
|
|
def _clean_csv(self, data):
|
|
|
|
stream = StringIO(data.strip())
|
|
|
|
reader = csv.reader(stream)
|
|
|
|
headers, records = parse_csv(reader)
|
|
|
|
|
|
|
|
# Set CSV headers for reference by the model form
|
|
|
|
self._csv_headers = headers
|
|
|
|
|
|
|
|
return records
|
|
|
|
|
|
|
|
def _clean_json(self, data):
|
|
|
|
try:
|
|
|
|
data = json.loads(data)
|
|
|
|
# Accommodate for users entering single objects
|
|
|
|
if type(data) is not list:
|
|
|
|
data = [data]
|
|
|
|
return data
|
|
|
|
except json.decoder.JSONDecodeError as err:
|
|
|
|
raise forms.ValidationError({
|
|
|
|
self.data_field: f"Invalid JSON data: {err}"
|
|
|
|
})
|
|
|
|
|
|
|
|
def _clean_yaml(self, data):
|
|
|
|
try:
|
|
|
|
return yaml.load_all(data, Loader=yaml.SafeLoader)
|
|
|
|
except yaml.error.YAMLError as err:
|
|
|
|
raise forms.ValidationError({
|
|
|
|
self.data_field: f"Invalid YAML data: {err}"
|
|
|
|
})
|
2020-08-11 15:09:23 -04:00
|
|
|
|
|
|
|
|
2021-11-19 15:12:45 -05:00
|
|
|
class FilterForm(BootstrapMixin, forms.Form):
|
|
|
|
"""
|
|
|
|
Base Form class for FilterSet forms.
|
|
|
|
"""
|
|
|
|
q = forms.CharField(
|
|
|
|
required=False,
|
2022-01-17 11:12:54 -05:00
|
|
|
label='Search'
|
2021-11-19 15:12:45 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2020-08-11 15:09:23 -04:00
|
|
|
class TableConfigForm(BootstrapMixin, forms.Form):
|
|
|
|
"""
|
|
|
|
Form for configuring user's table preferences.
|
|
|
|
"""
|
2021-04-12 10:46:32 -04:00
|
|
|
available_columns = forms.MultipleChoiceField(
|
|
|
|
choices=[],
|
|
|
|
required=False,
|
|
|
|
widget=forms.SelectMultiple(
|
2021-04-14 17:05:10 -07:00
|
|
|
attrs={'size': 10, 'class': 'form-select'}
|
2021-04-12 10:46:32 -04:00
|
|
|
),
|
2021-04-14 17:05:10 -07:00
|
|
|
label='Available Columns'
|
2021-04-12 10:46:32 -04:00
|
|
|
)
|
2020-08-11 15:09:23 -04:00
|
|
|
columns = forms.MultipleChoiceField(
|
|
|
|
choices=[],
|
2020-10-29 14:42:40 -04:00
|
|
|
required=False,
|
2020-08-11 15:09:23 -04:00
|
|
|
widget=forms.SelectMultiple(
|
2021-04-14 17:05:10 -07:00
|
|
|
attrs={'size': 10, 'class': 'form-select'}
|
2020-08-11 15:09:23 -04:00
|
|
|
),
|
2021-04-14 17:05:10 -07:00
|
|
|
label='Selected Columns'
|
2020-08-11 15:09:23 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
def __init__(self, table, *args, **kwargs):
|
2020-10-21 14:52:50 -04:00
|
|
|
self.table = table
|
|
|
|
|
2020-08-11 15:09:23 -04:00
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
# Initialize columns field based on table attributes
|
2021-04-12 10:46:32 -04:00
|
|
|
self.fields['available_columns'].choices = table.available_columns
|
|
|
|
self.fields['columns'].choices = table.selected_columns
|
2020-10-21 14:52:50 -04:00
|
|
|
|
|
|
|
@property
|
|
|
|
def table_name(self):
|
|
|
|
return self.table.__class__.__name__
|