diff options
Diffstat (limited to 'core/forms.py')
| -rw-r--r-- | core/forms.py | 103 |
1 files changed, 103 insertions, 0 deletions
diff --git a/core/forms.py b/core/forms.py new file mode 100644 index 0000000..1ade0fe --- /dev/null +++ b/core/forms.py @@ -0,0 +1,103 @@ +from django import forms +from django.forms import inlineformset_factory + +from .models import Product, Supplier, Order, OrderItem +from extra_views import InlineFormSetFactory + +class ProductForm(forms.ModelForm): + supplier_name = forms.CharField(label="Поставщик", required=True) + + class Meta: + model = Product + fields = [ + "article", + "name", + "unit", + "price", + "manufacturer", + "category", + "discount", + "quantity", + "description", + "photo", + ] + labels = { + "article": "Артикуль", + "name": "Название", + "unit": "Единица измерения", + "price": "Цена", + "manufacturer": "Производитель", + "category": "Категория", + "discount": "Скидка", + "quantity": "Колличество", + "description": "Описание", + "photo": "Фото", + } + widgets = { + "description": forms.Textarea(attrs={"rows": 3}) + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if self.instance.pk: + if self.instance.supplier: + self.fields["supplier_name"].initial = self.instance.supplier.name + + def save(self, commit=True): + supplier, _ = Supplier.objects.get_or_create( + name=self.cleaned_data["supplier_name"].strip() + ) + + instance = super().save(commit=False) + instance.supplier = supplier + + if commit: + instance.save() + + return instance + + + def clean_price(self): + price = self.cleaned_data.get("price") + if price < 0: + raise forms.ValidationError("Цена не может быть отрицательной") + return price + + def clean_quantity(self): + quantity = self.cleaned_data.get("quantity") + if quantity < 0: + raise forms.ValidationError("Колличество не может быть отрицательной") + return quantity + + +class OrderForm(forms.ModelForm): + class Meta: + model = Order + fields = [ + "delivery_date", + "pickup_point", + "pickup_code", + "status", + ] + + labels = { + "order_date": "Дата заказа", + "delivery_date": "Дата доставки", + "pickup_point": "Пункт выдачи", + "client_name": "Имя клиента", + "pickup_code": "Код выдачи", + "status": "Статус", + "items": "Продукты", + } + widgets = { + "delivery_date": forms.SelectDateWidget + } + +class OrderItemFormSet(InlineFormSetFactory): + model = OrderItem + fields = ["product", "count"] + factory_kwargs = { + "extra": 1, + "can_delete": True, + "labels": {"product": "Продукт", "count": "Количество"} + } |
