Moved category templates processing to Part save() method

This commit is contained in:
eeintech 2020-11-04 09:52:26 -05:00
parent 9eba564ff6
commit 1c14c2237a
5 changed files with 57 additions and 45 deletions

View File

@ -219,10 +219,10 @@ class SettingCategorySelectForm(forms.ModelForm):
Div( Div(
Div(Field('category'), Div(Field('category'),
css_class='col-sm-6', css_class='col-sm-6',
style='width: 30%;'), style='width: 70%;'),
Div(StrictButton(_('Select Category'), css_class='btn btn-primary', type='submit'), Div(StrictButton(_('Select Category'), css_class='btn btn-primary', type='submit'),
css_class='col-sm-6', css_class='col-sm-6',
style='width: auto; padding-left: 0;'), style='width: 30%; padding-left: 0;'),
css_class='row', css_class='row',
), ),
) )

View File

@ -86,9 +86,9 @@ class InvenTreeSetting(models.Model):
}, },
'PART_CATEGORY_PARAMETERS': { 'PART_CATEGORY_PARAMETERS': {
'name': _('Create Parameters From Category Templates'), 'name': _('Copy Category Parameter Templates'),
'description': _('Automatically create part parameters from category templates'), 'description': _('Copy category parameter templates when creating a part'),
'default': False, 'default': True,
'validator': bool 'validator': bool
}, },

View File

@ -12,6 +12,7 @@ from django.core.exceptions import ValidationError
from django.urls import reverse from django.urls import reverse
from django.db import models, transaction from django.db import models, transaction
from django.db.utils import IntegrityError
from django.db.models import Sum, UniqueConstraint from django.db.models import Sum, UniqueConstraint
from django.db.models.functions import Coalesce from django.db.models.functions import Coalesce
from django.core.validators import MinValueValidator from django.core.validators import MinValueValidator
@ -324,6 +325,9 @@ class Part(MPTTModel):
If not, it is considered "orphaned" and will be deleted. If not, it is considered "orphaned" and will be deleted.
""" """
# Get category templates settings
add_category_templates = kwargs.pop('add_category_templates', None)
if self.pk: if self.pk:
previous = Part.objects.get(pk=self.pk) previous = Part.objects.get(pk=self.pk)
@ -339,6 +343,44 @@ class Part(MPTTModel):
super().save(*args, **kwargs) super().save(*args, **kwargs)
if add_category_templates:
# Get part category
category = self.category
if add_category_templates:
# Store templates added to part
template_list = []
# Create part parameters for selected category
category_templates = add_category_templates['main']
if category_templates:
for template in category.get_parameter_templates():
parameter = PartParameter.create(part=self,
template=template.parameter_template,
data=template.default_value,
save=True)
if parameter:
template_list.append(template.parameter_template)
# Create part parameters for parent category
category_templates = add_category_templates['parent']
if category_templates:
# Get parent categories
parent_categories = category.get_ancestors()
for category in parent_categories:
for template in category.get_parameter_templates():
# Check that template wasn't already added
if template.parameter_template not in template_list:
try:
PartParameter.create(part=self,
template=template.parameter_template,
data=template.default_value,
save=True)
except IntegrityError:
# PartParameter already exists
pass
def __str__(self): def __str__(self):
return f"{self.full_name} - {self.description}" return f"{self.full_name} - {self.description}"

View File

@ -684,7 +684,14 @@ class PartCreate(AjaxCreateView):
# Record the user who created this part # Record the user who created this part
part.creation_user = request.user part.creation_user = request.user
part.save() # Store category templates settings
add_category_templates = {
'main': form.cleaned_data['selected_category_templates'],
'parent': form.cleaned_data['parent_category_templates'],
}
# Save part and pass category template settings
part.save(**{'add_category_templates': add_category_templates})
data['pk'] = part.pk data['pk'] = part.pk
data['text'] = str(part) data['text'] = str(part)
@ -694,42 +701,6 @@ class PartCreate(AjaxCreateView):
except AttributeError: except AttributeError:
pass pass
# Store templates added to part
template_list = []
# Create part parameters for selected category
category_templates = form.cleaned_data['selected_category_templates']
if category_templates:
# Get selected category
category = form.cleaned_data['category']
for template in category.get_parameter_templates():
parameter = PartParameter.create(part=part,
template=template.parameter_template,
data=template.default_value,
save=True)
if parameter:
template_list.append(template.parameter_template)
# Create part parameters for parent category
category_templates = form.cleaned_data['parent_category_templates']
if category_templates:
# Get parent categories
parent_categories = form.cleaned_data['category'].get_ancestors()
for category in parent_categories:
for template in category.get_parameter_templates():
# Check that template wasn't already added
if template.parameter_template not in template_list:
try:
PartParameter.create(part=part,
template=template.parameter_template,
data=template.default_value,
save=True)
except IntegrityError:
# PartParameter already exists
pass
return self.renderJsonResponse(request, form, data, context=context) return self.renderJsonResponse(request, form, data, context=context)
def get_initial(self): def get_initial(self):

View File

@ -37,7 +37,8 @@
{% block js_ready %} {% block js_ready %}
{{ block.super }} {{ block.super }}
{# Convert dropdown to select2 format #}
$(document).ready(function() { $(document).ready(function() {
attachSelect('#category-select'); attachSelect('#category-select');
}); });
@ -78,7 +79,6 @@
] ]
}); });
$("#new-param").click(function() { $("#new-param").click(function() {
launchModalForm("{% url 'category-param-template-create' category.pk %}", { launchModalForm("{% url 'category-param-template-create' category.pk %}", {
success: function() { success: function() {
@ -110,6 +110,5 @@
} }
}); });
}); });
{% endif %} {% endif %}
{% endblock %} {% endblock %}