64 lines
2.3 KiB
Python
64 lines
2.3 KiB
Python
from django import forms
|
|
from django.core.exceptions import ValidationError
|
|
|
|
from shop.models import ProductVariant, Tax
|
|
|
|
|
|
class ProductInitialPriceForm(forms.Form):
|
|
"""Precio opcional que se puede fijar al crear un producto, junto con el
|
|
resto de datos, en el mismo envío (ver backoffice/views/products.py:ProductCreateView)."""
|
|
|
|
price = forms.DecimalField(
|
|
max_digits=11,
|
|
decimal_places=2,
|
|
required=False,
|
|
widget=forms.NumberInput(attrs={'class': 'input input-bordered w-full', 'step': '0.01', 'placeholder': 'Precio'}),
|
|
)
|
|
tax = forms.ModelChoiceField(
|
|
queryset=Tax.objects.all(),
|
|
required=False,
|
|
widget=forms.Select(attrs={'class': 'select select-bordered w-full'}),
|
|
)
|
|
|
|
def clean(self):
|
|
cleaned_data = super().clean()
|
|
|
|
if cleaned_data.get('price') is not None and not cleaned_data.get('tax'):
|
|
raise ValidationError('Selecciona un impuesto para el precio.')
|
|
|
|
if cleaned_data.get('tax') and cleaned_data.get('price') is None:
|
|
raise ValidationError('Indica un precio para el impuesto seleccionado.')
|
|
|
|
return cleaned_data
|
|
|
|
|
|
class ProductVariantForm(forms.ModelForm):
|
|
class Meta:
|
|
model = ProductVariant
|
|
fields = ('sku', 'stock', 'attribute_values')
|
|
widgets = {'attribute_values': forms.CheckboxSelectMultiple}
|
|
|
|
def __init__(self, *args, product=None, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
self.product = product or self.instance.product
|
|
|
|
def clean(self):
|
|
cleaned_data = super().clean()
|
|
attribute_values = cleaned_data.get('attribute_values')
|
|
|
|
if attribute_values is not None:
|
|
combination = set(attribute_values.values_list('pk', flat=True))
|
|
siblings = ProductVariant.objects.filter(product=self.product).exclude(pk=self.instance.pk)
|
|
|
|
for sibling in siblings:
|
|
if set(sibling.attribute_values.values_list('pk', flat=True)) == combination:
|
|
raise ValidationError(
|
|
'Ya existe una variante de este producto con la misma combinación de atributos.'
|
|
)
|
|
|
|
return cleaned_data
|
|
|
|
def save(self, commit=True):
|
|
self.instance.product = self.product
|
|
return super().save(commit=commit)
|