Динамическое создание формсета с нужным количеством форм для черновика
This commit is contained in:
@@ -137,32 +137,20 @@ def order_create(request):
|
|||||||
|
|
||||||
# Создаем formset с предзаполненными товарами из черновика
|
# Создаем formset с предзаполненными товарами из черновика
|
||||||
if draft_items:
|
if draft_items:
|
||||||
|
from django.forms import inlineformset_factory
|
||||||
from products.models import Product, ProductKit
|
from products.models import Product, ProductKit
|
||||||
initial_formset_data = []
|
|
||||||
|
|
||||||
for item in draft_items:
|
# Создаём формсет с нужным количеством extra форм
|
||||||
item_data = {
|
DraftOrderItemFormSet = inlineformset_factory(
|
||||||
'quantity': item['quantity'],
|
Order,
|
||||||
'price': item['price'],
|
OrderItem,
|
||||||
'is_custom_price': False,
|
form=OrderItemForm,
|
||||||
}
|
extra=len(draft_items), # Создаём столько форм, сколько товаров
|
||||||
|
can_delete=True,
|
||||||
if item['type'] == 'product':
|
min_num=0,
|
||||||
try:
|
validate_min=False,
|
||||||
product = Product.objects.get(id=item['id'])
|
)
|
||||||
item_data['product'] = product.id
|
formset = DraftOrderItemFormSet()
|
||||||
initial_formset_data.append(item_data)
|
|
||||||
except Product.DoesNotExist:
|
|
||||||
pass
|
|
||||||
elif item['type'] in ['kit', 'showcase_kit']:
|
|
||||||
try:
|
|
||||||
kit = ProductKit.objects.get(id=item['id'])
|
|
||||||
item_data['product_kit'] = kit.id
|
|
||||||
initial_formset_data.append(item_data)
|
|
||||||
except ProductKit.DoesNotExist:
|
|
||||||
pass
|
|
||||||
|
|
||||||
formset = OrderItemFormSet(initial=initial_formset_data)
|
|
||||||
else:
|
else:
|
||||||
formset = OrderItemFormSet()
|
formset = OrderItemFormSet()
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user