Try out some stuff

This commit is contained in:
Mario Hüttel 2021-12-31 16:38:23 +01:00
parent ca61437110
commit 258fd1747c
5 changed files with 32 additions and 212 deletions

View File

@ -1,8 +1,18 @@
from django import forms from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from parts import models as parts_models from parts import models as parts_models
from shimatta_modules.EngineeringNumberConverter import EngineeringNumberConverter 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): class MyTestForm(forms.Form):
pass 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 = parts_models.Stock.objects.create(storage=storage, component=component, watermark=watermark, amount=amount, lot=self.cleaned_data['lot'])
new_stock.save() 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): class EditComponentForm(forms.Form):
name = forms.CharField(required=True) 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.component_type = self.cleaned_data['component_type_object']
self.instance.save() 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 PackageForm(forms.ModelForm):
class Meta: class Meta:

View File

@ -519,15 +519,10 @@ class ComponentDetailView(LoginRequiredMixin, BaseTemplateMixin, DetailView):
context = super().get_context_data(**kwargs) context = super().get_context_data(**kwargs)
context['component'] = self.object context['component'] = self.object
context['edit_form'] = EditComponentForm(instance=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['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 return context
def handle_submit_edit_post(self, request, **kwargs): def handle_submit_edit_post(self, request, **kwargs):
@ -551,77 +546,10 @@ class ComponentDetailView(LoginRequiredMixin, BaseTemplateMixin, DetailView):
context['edit_form'] = form context['edit_form'] = form
return self.render_to_response(context) 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): def post(self, request, *args, **kwargs):
self.object = self.get_object() self.object = self.get_object()
if 'submit-edit-comp' in request.POST: if 'submit-edit-comp' in request.POST:
return self.handle_submit_edit_post(request, **kwargs) 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) return super().post(request, *args, **kwargs)

View File

@ -46,8 +46,11 @@ INSTALLED_APPS = [
'rest_framework', 'rest_framework',
'crispy_forms', 'crispy_forms',
'crispy_bootstrap5', 'crispy_bootstrap5',
'django.forms',
] ]
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
MIDDLEWARE = [ MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware', 'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',

View File

@ -95,74 +95,10 @@
<div class="row"> <div class="row">
<div class="col"> <div class="col">
<h3>Parameters</h3> <h3>Parameters</h3>
<form method="post">
{% csrf_token %}
<table class="table">
<thead>
<th scope="col">Parameter</th>
<th scope="col">Value</th>
<th scope="col">Unit</th>
</thead>
<tbody>
{% for f in param_formset %}
<tr>
<td><input type="text" class="form-control{% if f.parameter_type.errors %} is-invalid{% endif %}" name="{{f.parameter_type.html_name}}" value="{{f.parameter_type.value}}"></td>
<td><input type="text" class="form-control{% if f.value.errors %} is-invalid{% endif %}" name="{{f.value.html_name}}" value="{{f.value.value}}"></td>
<td>{{f.parameter_type_object.unit|default_if_none:"-"}}</td>
</tr>
{% if f.errors %}
<tr class="text-danger">
<td>
{% if f.parameter_type.errors %}
{{f.parameter_type.errors}}
{% endif %}
</td>
<td>
{% if f.value.errors %}
{{f.value.errors}}
{% endif %}
</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
{{param_formset.management_form}}
<input type="submit" class="btn btn-primary" name="submit-edit-params" value="Save Parameters">
</form>
</div> </div>
<div class="col"> <div class="col">
<h3>Distributor Part Numbers</h3> <h3>Distributor Part Numbers</h3>
<form method="post">
{% csrf_token %}
<table class="table">
<thead>
<th scope="col">Distributor</th>
<th scope="col">Part Number</th>
</thead>
<tbody>
{% for form in distri_num_formset %}
<tr>
<td>
{% if form.instance.distributor %}
{{form.instance.distributor.name}}
{% else %}
<input type="text" name="__unused_search" id="{{form.distributor.id_for_label}}-search">
{% endif %}
</td>
<input type="hidden" name="{{form.distributor.html_name}}" id="{{form.distributor.id_for_label}}" value="{{form.distributor.value|default_if_none:""}}">
<input type="hidden" name="{{form.id.html_name}}" value="{{form.id.value|default_if_none:""}}">
<td>
<input class="form-control" type="text" name="{{form.distributor_part_number.html_name}}" id="{{form.distributor_part_number.id_for_label}}" value="{{form.distributor_part_number.value|default_if_none:""}}">
</td>
</tr>
{% endfor %}
</tbody>
</table>
{{distri_num_formset.management_form}}
<input type="submit" class="btn btn-secondary" name="submit-edit-distri-nums" value="Save">
</form>
</div> </div>
</div> </div>
<div class="row mt-2"> <div class="row mt-2">
@ -183,6 +119,9 @@
</div> </div>
</div> </div>
</div> </div>
{{comp_form|crispy}}
</div> </div>
{% if component.get_resolved_image %} {% if component.get_resolved_image %}

View File

@ -0,0 +1,7 @@
<div class="dropdown">
<input autocomplete="off" data-bs-toggle="dropdown" class="form-control{% if widget.errors %} is-invalid{% endif %}" type="text" {% if widget.value != None %}value="{{widget.value}}"{%endif%}
{% for name, value in widget.attrs.items %}{% if value is not False and name != 'id' %} {{ name }}{% if value is not True %}="{{ value|stringformat:'s' }}"{% endif %}{% endif %}{% endfor %} id="{{widget.attrs.id}}_search_field">
<ul id="{{form.manufacturer.id_for_label}}-ac-ul" class="dropdown-menu">
</ul>
<input type="hidden" value="" name={{widget.name}}>
</div>