from django import forms from django.contrib.auth import get_user_model from .models import Color, Feedback, Manufacturer, Printer, ProductType, Variant def selection_id(value): text = str(value or "") return int(text) if text.isascii() and text.isdecimal() and len(text) < 19 else None class ProfileForm(forms.ModelForm): class Meta: model = get_user_model() fields = ["first_name", "last_name", "email"] class PrinterForm(forms.ModelForm): class Meta: model = Printer fields = ["manufacturer", "model", "name"] class FeedbackForm(forms.ModelForm): class Meta: model = Feedback fields = ["message"] widgets = {"message": forms.Textarea(attrs={"rows": 6})} class QuantityForm(forms.Form): quantity = forms.IntegerField(label="Stückzahl", min_value=1, max_value=9999) class ConsumeSpoolForm(forms.Form): quantity = forms.IntegerField(min_value=1, max_value=9999, widget=forms.HiddenInput) action = forms.ChoiceField(choices=[("consume", "Verbrauchen"), ("reorder", "Nachbestellen")]) class SubtypeChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.material_and_subtype[1] class ColorSelect(forms.Select): def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): option = super().create_option(name, value, label, selected, index, subindex, attrs) if value and (swatch := self.swatches.get(value.instance.pk)): option["attrs"]["data-swatch"] = swatch return option class VariantSelectionForm(forms.Form): manufacturer = forms.ModelChoiceField( label="Hersteller", queryset=Manufacturer.objects.none(), empty_label="Hersteller wählen" ) material = forms.ChoiceField(label="Material", choices=[]) product_type = SubtypeChoiceField( label="Unterart", queryset=ProductType.objects.none(), empty_label="Unterart wählen" ) color = forms.ModelChoiceField( label="Farbe", queryset=Color.objects.none(), empty_label="Farbe wählen", widget=ColorSelect(attrs={"data-color-select": ""}), ) spool_type = forms.ChoiceField(label="Spulenausführung", choices=[]) quantity = forms.IntegerField(label="Stückzahl", min_value=1, max_value=9999, initial=1) def __init__(self, *args, selection=None, **kwargs): super().__init__(*args, **kwargs) values = self.data if self.is_bound else (selection or {}) if not self.is_bound: self.initial.update({k: values[k] for k in self.fields if k in values}) active = Variant.objects.filter(is_active=True) maker = selection_id(values.get("manufacturer")) product = selection_id(values.get("product_type")) color = selection_id(values.get("color")) self.fields["manufacturer"].queryset = Manufacturer.objects.filter( producttype__variants__in=active ).distinct() products = ( ProductType.objects.filter(manufacturer_id=maker, variants__in=active) .select_related("manufacturer") .distinct() ) selected_material = values.get("material") materials = {} for candidate in products: material = candidate.material_and_subtype[0] materials.setdefault(material, []).append(candidate.pk) self.fields["material"].choices = [("", "Material wählen")] + [ (material, material) for material in sorted(materials, key=str.casefold) ] allowed_products = materials.get(selected_material, []) self.fields["product_type"].queryset = products.filter(pk__in=allowed_products) narrowed = active.filter(product_type_id=product, product_type_id__in=allowed_products) self.fields["color"].queryset = Color.objects.filter(variants__in=narrowed).distinct() # Prefer the spool's preview when the two packaging variants have different values. self.fields["color"].widget.swatches = dict( narrowed.exclude(swatch="") .order_by("spool_type", "pk") .values_list("color_id", "swatch") ) spools = set(narrowed.filter(color_id=color).values_list("spool_type", flat=True)) self.fields["spool_type"].choices = [("", "Spulenausführung wählen")] + [ (key, label) for key, label in Variant.SpoolType.choices if key in spools ] def clean(self): cleaned = super().clean() if all( cleaned.get(k) for k in ("manufacturer", "material", "product_type", "color", "spool_type") ): self.variant = Variant.objects.filter( is_active=True, product_type=cleaned["product_type"], product_type__manufacturer=cleaned["manufacturer"], color=cleaned["color"], spool_type=cleaned["spool_type"], ).first() if self.variant is None: raise forms.ValidationError( "Diese Variante ist nicht mehr verfügbar. Bitte neu auswählen." ) return cleaned