diff --git a/shimatta_kenkyusho/parts/forms.py b/shimatta_kenkyusho/parts/forms.py index 504d763..4080327 100644 --- a/shimatta_kenkyusho/parts/forms.py +++ b/shimatta_kenkyusho/parts/forms.py @@ -1,8 +1,18 @@ from django import forms +from django.forms import widgets from django.core.exceptions import ValidationError from parts import models as parts_models from shimatta_modules.EngineeringNumberConverter import EngineeringNumberConverter + +class AutoCompleteWidget(widgets.TextInput): + template_name = 'widgets/autrocomplete-foreign-key.html' + +class AutocompleteForeingKeyField(forms.UUIDField): + def __init__(self, foreign_model=None, api_search_url=None, autocomplete_media_div=False, **kwargs): + kwargs['widget'] = AutoCompleteWidget + super().__init__(**kwargs) + class MyTestForm(forms.Form): pass @@ -106,6 +116,13 @@ class AddStockForm(forms.Form): new_stock = parts_models.Stock.objects.create(storage=storage, component=component, watermark=watermark, amount=amount, lot=self.cleaned_data['lot']) new_stock.save() + +class ComponentForm(forms.ModelForm): + manufacturer = AutocompleteForeingKeyField(widget=AutoCompleteWidget) + component_type = AutocompleteForeingKeyField() + class Meta: + model = parts_models.Component + fields = '__all__' class EditComponentForm(forms.Form): name = forms.CharField(required=True) @@ -219,80 +236,6 @@ class EditComponentForm(forms.Form): self.instance.component_type = self.cleaned_data['component_type_object'] self.instance.save() -class EditComponentParameterForm(forms.Form): - parameter_type = forms.CharField(initial='') # This must come first. Do not change the order of these elements! - value = forms.CharField(initial='') - - def __init__(self, *args, **kwargs): - - init_values = kwargs.get('initial', None) - if init_values is not None: - if isinstance(init_values['parameter_type'], parts_models.ComponentParameterType): - type_instance = init_values['parameter_type'] - self.parameter_type_object = type_instance - kwargs['initial']['parameter_type'] = init_values['parameter_type'].parameter_name - if isinstance(init_values['value'], int) or isinstance(init_values['value'], float): - if type_instance.parameter_type == 'E': - (num, prefix) = EngineeringNumberConverter.number_to_engineering(init_values['value'], False) - kwargs['initial']['value'] = f'{num}{prefix}' - elif type_instance.parameter_type == 'I': - (num, prefix) = EngineeringNumberConverter.number_to_engineering(init_values['value'], True) - kwargs['initial']['value'] = f'{num}{prefix}' - - super().__init__(*args, **kwargs) - - def clean_parameter_type(self): - data = self.cleaned_data['parameter_type'] - - param_instance = None - try: - param_instance = parts_models.ComponentParameterType.objects.get(parameter_name=data) - except: - raise ValidationError(f'Component Parameter Type {data} is not defined') - - self.cleaned_data['parameter_type_object'] = param_instance - return data - - def clean_value(self): - parameter_type = self.cleaned_data.get('parameter_type_object', None) - value_data = self.cleaned_data['value'] - - if parameter_type is None: - raise ValidationError('Cannot convert value for unknown parameter type') - - processed_value = None - - if parameter_type.parameter_type == 'E' or parameter_type.parameter_type == 'I': - try: - processed_value = EngineeringNumberConverter.engineering_to_number(value_data) - except: - raise ValidationError(f'Cannot not convert Value "{value_data}" to a number') - elif parameter_type.parameter_type == 'F': - processed_value = value_data - else: - try: - processed_value = float(value_data) - except: - raise ValidationError(f'"{value_data}" is not a valid number') - - self.cleaned_data['processed_value'] = processed_value - - return value_data - - -class DistributorNumberForm(forms.ModelForm): - class Meta: - model = parts_models.DistributorNum - fields = ['distributor', 'distributor_part_number'] - -class DistributorNumberFormSet(forms.BaseModelFormSet): - def save(self, component, commit=True): - instances = super().save(commit=False) - for instance in instances: - instance.component = component - if commit: - instance.save() - return instances class PackageForm(forms.ModelForm): class Meta: diff --git a/shimatta_kenkyusho/parts/views.py b/shimatta_kenkyusho/parts/views.py index c9fb206..8058f88 100644 --- a/shimatta_kenkyusho/parts/views.py +++ b/shimatta_kenkyusho/parts/views.py @@ -519,15 +519,10 @@ class ComponentDetailView(LoginRequiredMixin, BaseTemplateMixin, DetailView): context = super().get_context_data(**kwargs) context['component'] = self.object context['edit_form'] = EditComponentForm(instance=self.object) - - ParameterFormset = forms.formset_factory(EditComponentParameterForm, extra=1, max_num=100, can_delete=True) - context['param_formset'] = ParameterFormset( - initial=self.prepare_initial_param_formset_data()) context['stocks'] = Stock.objects.filter(component=self.object) + context['comp_form'] = ComponentForm() - DistriNumFormSet = forms.modelformset_factory(DistributorNum, form=DistributorNumberForm, extra=2) - context['distri_num_formset'] = DistriNumFormSet(queryset=DistributorNum.objects.filter(component=self.object), auto_id='id_fs_distri_no_%s') return context def handle_submit_edit_post(self, request, **kwargs): @@ -551,77 +546,10 @@ class ComponentDetailView(LoginRequiredMixin, BaseTemplateMixin, DetailView): context['edit_form'] = form return self.render_to_response(context) - def handle_submit_edit_params_post(self, request, **kwargs): - ParameterFormset = forms.formset_factory(EditComponentParameterForm, extra=1, max_num=100) - fs = ParameterFormset(initial=self.prepare_initial_param_formset_data(), data=request.POST) - errors_set = False - - if fs.is_valid(): - # Go through all the parameter forms: - for form in fs: - if not form.has_changed(): - continue - - # Form has changed. Process the new value - try: - parameter_to_change = ComponentParameter.objects.get(component=self.object, - parameter_type__parameter_name=form.initial['parameter_type']) - parameter_to_change.parameter_type = form.cleaned_data['parameter_type_object'] - parameter_to_change.value = 0 - parameter_to_change.text_value = None - except: - try: - parameter_to_change = ComponentParameter.objects.create(component=self.object, - parameter_type=form.cleaned_data['parameter_type_object']) - except: - form.add_error('parameter_type', 'Parameter could not be saved. Unique?') - errors_set = True - break - - parameter_to_change.value = 0 - parameter_to_change.text_value = None - - if parameter_to_change.parameter_type.parameter_type == 'F': - parameter_to_change.text_value = form.cleaned_data['processed_value'] - parameter_to_change.value = 0 - else: - parameter_to_change.value = form.cleaned_data['processed_value'] - - try: - parameter_to_change.save() - except: - form.add_error('parameter_type', 'Parameter could not be saved. Unique?') - errors_set = True - - context = self.get_context_data() - if not fs.is_valid() or errors_set: - context['param_formset'] = fs - return self.render_to_response(context) - - def handle_submit_edit_distri_nums_post(self, request, **kwargs): - DistriNumFormSet = forms.modelformset_factory(DistributorNum, form=DistributorNumberForm, extra=2, formset=DistributorNumberFormSet) - fs = DistriNumFormSet(queryset=DistributorNum.objects.filter(component=self.object), data=request.POST, auto_id='id_fs_distri_no_%s') - - if fs.is_valid(): - print('Valid') - fs.save(self.object) - else: - print('Invalid') - - context = self.get_context_data() - if not fs.is_valid(): - context['distri_num_formset'] = fs - return self.render_to_response(context) - - def post(self, request, *args, **kwargs): self.object = self.get_object() if 'submit-edit-comp' in request.POST: return self.handle_submit_edit_post(request, **kwargs) - elif 'submit-edit-params' in request.POST: - return self.handle_submit_edit_params_post(request, **kwargs) - elif 'submit-edit-distri-nums' in request.POST: - return self.handle_submit_edit_distri_nums_post(request, **kwargs) return super().post(request, *args, **kwargs) diff --git a/shimatta_kenkyusho/shimatta_kenkyusho/settings.py b/shimatta_kenkyusho/shimatta_kenkyusho/settings.py index ecb4816..9905e0e 100644 --- a/shimatta_kenkyusho/shimatta_kenkyusho/settings.py +++ b/shimatta_kenkyusho/shimatta_kenkyusho/settings.py @@ -46,8 +46,11 @@ INSTALLED_APPS = [ 'rest_framework', 'crispy_forms', 'crispy_bootstrap5', + 'django.forms', ] +FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' + MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', diff --git a/shimatta_kenkyusho/templates/parts/components-detail.html b/shimatta_kenkyusho/templates/parts/components-detail.html index 566a2e5..bd16760 100644 --- a/shimatta_kenkyusho/templates/parts/components-detail.html +++ b/shimatta_kenkyusho/templates/parts/components-detail.html @@ -95,74 +95,10 @@

Parameters

-
- {% csrf_token %} - - - - - - - - {% for f in param_formset %} - - - - - - {% if f.errors %} - - - - - {% endif %} - {% endfor %} - -
ParameterValueUnit
{{f.parameter_type_object.unit|default_if_none:"-"}}
- {% if f.parameter_type.errors %} - {{f.parameter_type.errors}} - {% endif %} - - {% if f.value.errors %} - {{f.value.errors}} - {% endif %} -
- {{param_formset.management_form}} - -

Distributor Part Numbers

-
- {% csrf_token %} - - - - - - - {% for form in distri_num_formset %} - - - - - - - - {% endfor %} - -
DistributorPart Number
- {% if form.instance.distributor %} - {{form.instance.distributor.name}} - {% else %} - - {% endif %} - - -
- {{distri_num_formset.management_form}} - -
+
@@ -183,6 +119,9 @@
+ + {{comp_form|crispy}} + {% if component.get_resolved_image %} diff --git a/shimatta_kenkyusho/templates/widgets/autrocomplete-foreign-key.html b/shimatta_kenkyusho/templates/widgets/autrocomplete-foreign-key.html new file mode 100644 index 0000000..8d25d3e --- /dev/null +++ b/shimatta_kenkyusho/templates/widgets/autrocomplete-foreign-key.html @@ -0,0 +1,7 @@ + \ No newline at end of file