Files
Fil-A-Management/filament/forms.py
T

102 lines
4.1 KiB
Python

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 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"
)
product_type = forms.ModelChoiceField(
label="Produktart", queryset=ProductType.objects.none(), empty_label="Produktart 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()
self.fields["product_type"].queryset = ProductType.objects.filter(
manufacturer_id=maker, variants__in=active
).distinct()
narrowed = active.filter(product_type__manufacturer_id=maker, product_type_id=product)
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", "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