2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-06-17 20:45:44 +00:00
Files
InvenTree/InvenTree/common/forms.py
Matthias Mair 0c97a50e47 Docstring checks in QC checks (#3089)
* Add pre-commit to the stack

* exclude static

* Add locales to excludes

* fix style errors

* rename pipeline steps

* also wait on precommit

* make template matching simpler

* Use the same code for python setup everywhere

* use step and cache for python setup

* move regular settings up into general envs

* just use full update

* Use invoke instead of static references

* make setup actions more similar

* use python3

* refactor names to be similar

* fix runner version

* fix references

* remove incidential change

* use matrix for os

* Github can't do this right now

* ignore docstyle errors

* Add seperate docstring test

* update flake call

* do not fail on docstring

* refactor setup into workflow

* update reference

* switch to action

* resturcture

* add bash statements

* remove os from cache

* update input checks

* make code cleaner

* fix boolean

* no relative paths

* install wheel by python

* switch to install

* revert back to simple wheel

* refactor import export tests

* move setup keys back to not disturbe tests

* remove docstyle till that is fixed

* update references

* continue on error

* add docstring test

* use relativ action references

* Change step / job docstrings

* update to merge

* reformat comments 1

* fix docstrings 2

* fix docstrings 3

* fix docstrings 4

* fix docstrings 5

* fix docstrings 6

* fix docstrings 7

* fix docstrings 8

* fix docstirns 9

* fix docstrings 10

* docstring adjustments

* update the remaining docstrings

* small docstring changes

* fix function name

* update support files for docstrings

* Add missing args to docstrings

* Remove outdated function

* Add docstrings for the 'build' app

* Make API code cleaner

* add more docstrings for plugin app

* Remove dead code for plugin settings
No idea what that was even intended for

* ignore __init__ files for docstrings

* More docstrings

* Update docstrings for the 'part' directory

* Fixes for related_part functionality

* Fix removed stuff from merge 99676ee

* make more consistent

* Show statistics for docstrings

* add more docstrings

* move specific register statements to make them clearer to understant

* More docstrings for common

* and more docstrings

* and more

* simpler call

* docstrings for notifications

* docstrings for common/tests

* Add docs for common/models

* Revert "move specific register statements to make them clearer to understant"

This reverts commit ca96654622.

* use typing here

* Revert "Make API code cleaner"

This reverts commit 24fb68bd3e.

* docstring updates for the 'users' app

* Add generic Meta info to simple Meta classes

* remove unneeded unique_together statements

* More simple metas

* Remove unnecessary format specifier

* Remove extra json format specifiers

* Add docstrings for the 'plugin' app

* Docstrings for the 'label' app

* Add missing docstrings for the 'report' app

* Fix build test regression

* Fix top-level files

* docstrings for InvenTree/InvenTree

* reduce unneeded code

* add docstrings

* and more docstrings

* more docstrings

* more docstrings for stock

* more docstrings

* docstrings for order/views

* Docstrings for various files in the 'order' app

* Docstrings for order/test_api.py

* Docstrings for order/serializers.py

* Docstrings for order/admin.py

* More docstrings for the order app

* Add docstrings for the 'company' app

* Add unit tests for rebuilding the reference fields

* Prune out some more dead code

* remove more dead code

Co-authored-by: Oliver Walters <oliver.henry.walters@gmail.com>
2022-06-02 01:37:39 +10:00

195 lines
7.0 KiB
Python

"""Django forms for interacting with common objects."""
from django import forms
from django.utils.translation import gettext as _
from InvenTree.forms import HelperForm
from .files import FileManager
from .models import InvenTreeSetting
class SettingEditForm(HelperForm):
"""Form for creating / editing a settings object."""
class Meta:
"""Metaclassoptions for SettingEditForm."""
model = InvenTreeSetting
fields = [
'value'
]
class UploadFileForm(forms.Form):
"""Step 1 of FileManagementFormView."""
file = forms.FileField(
label=_('File'),
help_text=_('Select file to upload'),
)
def __init__(self, *args, **kwargs):
"""Update label and help_text."""
# Get file name
name = None
if 'name' in kwargs:
name = kwargs.pop('name')
super().__init__(*args, **kwargs)
if name:
# Update label and help_text with file name
self.fields['file'].label = _(f'{name.title()} File')
self.fields['file'].help_text = _(f'Select {name} file to upload')
def clean_file(self):
"""Run tabular file validation.
If anything is wrong with the file, it will raise ValidationError
"""
file = self.cleaned_data['file']
# Validate file using FileManager class - will perform initial data validation
# (and raise a ValidationError if there is something wrong with the file)
FileManager.validate(file)
return file
class MatchFieldForm(forms.Form):
"""Step 2 of FileManagementFormView."""
def __init__(self, *args, **kwargs):
"""Setup filemanager and check columsn."""
# Get FileManager
file_manager = None
if 'file_manager' in kwargs:
file_manager = kwargs.pop('file_manager')
super().__init__(*args, **kwargs)
# Setup FileManager
file_manager.setup()
# Get columns
columns = file_manager.columns()
# Get headers choices
headers_choices = [(header, header) for header in file_manager.HEADERS]
# Create column fields
for col in columns:
field_name = col['name']
self.fields[field_name] = forms.ChoiceField(
choices=[('', '-' * 10)] + headers_choices,
required=False,
widget=forms.Select(attrs={
'class': 'select fieldselect',
})
)
if col['guess']:
self.fields[field_name].initial = col['guess']
class MatchItemForm(forms.Form):
"""Step 3 of FileManagementFormView."""
def __init__(self, *args, **kwargs):
"""Setup filemanager and create fields."""
# Get FileManager
file_manager = None
if 'file_manager' in kwargs:
file_manager = kwargs.pop('file_manager')
if 'row_data' in kwargs:
row_data = kwargs.pop('row_data')
else:
row_data = None
super().__init__(*args, **kwargs)
# Setup FileManager
file_manager.setup()
# Create fields
if row_data:
# Navigate row data
for row in row_data:
# Navigate column data
for col in row['data']:
# Get column matching
col_guess = col['column'].get('guess', None)
# Set field name
field_name = col_guess.lower() + '-' + str(row['index'])
# check if field def was overriden
overriden_field = self.get_special_field(col_guess, row, file_manager)
if overriden_field:
self.fields[field_name] = overriden_field
# Create input for required headers
elif col_guess in file_manager.REQUIRED_HEADERS:
# Get value
value = row.get(col_guess.lower(), '')
# Set field input box
self.fields[field_name] = forms.CharField(
required=True,
initial=value,
)
# Create item selection box
elif col_guess in file_manager.OPTIONAL_MATCH_HEADERS:
# Get item options
item_options = [(option.id, option) for option in row['match_options_' + col_guess]]
# Get item match
item_match = row['match_' + col_guess]
# Set field select box
self.fields[field_name] = forms.ChoiceField(
choices=[('', '-' * 10)] + item_options,
required=False,
widget=forms.Select(attrs={
'class': 'select bomselect',
})
)
# Update select box when match was found
if item_match:
self.fields[field_name].initial = item_match.id
# Create item selection box
elif col_guess in file_manager.ITEM_MATCH_HEADERS:
# Get item options
item_options = [(option.id, option) for option in row['item_options']]
# Get item match
item_match = row['item_match']
# Set field name
field_name = 'item_select-' + str(row['index'])
# Set field select box
self.fields[field_name] = forms.ChoiceField(
choices=[('', '-' * 10)] + item_options,
required=False,
widget=forms.Select(attrs={
'class': 'select bomselect',
})
)
# Update select box when match was found
if item_match:
# Make it a required field: does not validate if
# removed using JS function
# self.fields[field_name].required = True
# Update initial value
self.fields[field_name].initial = item_match.id
# Optional entries
elif col_guess in file_manager.OPTIONAL_HEADERS:
# Get value
value = row.get(col_guess.lower(), '')
# Set field input box
self.fields[field_name] = forms.CharField(
required=False,
initial=value,
)
def get_special_field(self, col_guess, row, file_manager):
"""Function to be overriden in inherited forms to add specific form settings."""
return None