у меня имеется сайт(интернет-магазин) со всеми рабочими функциями. Я решил добавить к нему готовую html-страницу с использованием JavaScript, на которой будет мой каталог товаров и форма для заказа, но я не понимаю, как можно передать товары, которые я выберу, в базу данных в обход корзины.
Моя модель заказа:
class Order(models.Model):
user_id = models.IntegerField(null=True)
first_name = models.CharField(max_length=20, verbose_name=u"Имя")
last_name = models.CharField(max_length=30, verbose_name=u"Фамилия")
phone_number = PhoneNumberField(null = False, blank = False, verbose_name=u"Номер телефона", default=u"+7")
email = models.EmailField()
address = models.CharField(max_length=250, verbose_name=u"Адрес")
ddate = models.DateField(default=date.today, verbose_name=u"День доставки")
dtime = models.TimeField(default=timezone.now, verbose_name=u"Время доставки")
comment = models.CharField(max_length=256, blank=True, verbose_name=u"Комментарий к заказу")
howdelivery = models.CharField(max_length=50, verbose_name=u"Способ доставки")
howpay = models.CharField(max_length=50, verbose_name=u"Способ оплаты")
coupon = models.ForeignKey(Coupon,
related_name='orders',
null=True,
blank=True,
on_delete=models.CASCADE)
discount = models.IntegerField(default=0,
validators=[MinValueValidator(0),
])
created = models.DateTimeField(auto_now_add=True, verbose_name=u"Создан")
updated = models.DateTimeField(auto_now=True, verbose_name=u"Последнее ебновление")
paid = models.BooleanField(default=False, verbose_name=u"Оплачен")
class Meta:
ordering = ('-created',)
verbose_name = 'Заказ'
verbose_name_plural = 'Заказы'
def __str__(self):
return 'Order {}'.format(self.id)
def get_total_cost(self):
total_cost = sum(item.get_cost() for item in self.items.all())
return total_cost - total_cost * (self.discount / Decimal('100'))
class OrderItem(models.Model):
order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE)
product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=0)
quantity = models.PositiveIntegerField(default=1, verbose_name=u"Количество")
def __str__(self):
return '{}'.format(self.id)
def get_cost(self):
return self.price * self.quantity
Мой view:
def torder_create(request):
products = Product.objects.filter(available=True)
cart_product_form = CartAddProductForm()
cart = Cart(request)
if request.method == 'POST':
form = TOrderCreateForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
for item in cart:
OrderItem.objects.create(order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity'])
myorders_item = OrderItem.objects.filter()
mail_subject = 'Заказ успешно оформлен!'
html_message = render_to_string('orderemail.html', {'order': order,
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, html_message, to=[to_email]
)
email.send()
# очистка корзины
cart.clear()
return render(request, 'orders/order/created.html',
{'order': order})
else:
form = TOrderCreateForm
return render(request, 'telegram.html',
{'cart': cart, 'form': form, 'products': products, 'cart_product_form': cart_product_form,
})
Часть html-шаблона с страницей заказа:
<section class="cafe-page cafe-order-overview">
<div class="cafe-block">
<div class="cafe-order-header-wrap">
<h2 class="cafe-order-header">Ваш заказ</h2>
<span class="cafe-order-edit js-order-edit">Редактировать</span>
</div>
<div class="cafe-order-items">
{% for product in products %}
<div class="cafe-order-item js-order-item" data-item-id="{{ product.id }}">
<div class="cafe-order-item-photo">
<picture class="cafe-item-lottie js-item-lottie">
<source type="application/x-tgsticker" srcset="/img/cafe/Burger.tgs">
<img src="{% if product.image %}{{ product.image.url }}{% else %}{% static "img/no_image.png" %}{% endif %}" style="background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaH...');">
</picture>
</div>
<div class="cafe-order-item-label">
<div class="cafe-order-item-title">{{ product.name }} <span class="cafe-order-item-counter"><span class="js-order-item-counter">1</span>x</span></div>
<div class="cafe-order-item-description">{{ product.description|linebreaks }}</div>
</div>
<div class="cafe-order-item-price js-order-item-price">{{ product.price }}₽ </div>
</div>
{% endfor %}
<div class="cafe-text-field-wrap">
<form action="." method="post" class="order-form">
{{ form.as_p }}
{% csrf_token %}
<textarea class="cafe-text-field js-order-fname-field cafe-block" rows="1" type="text" name="first_name" maxlength="50" value="" required="" id="id_first_name" placeholder="Имя…"></textarea>
<textarea class="cafe-text-field js-order-lname-field cafe-block" rows="1" type="text" name="last_name" maxlength="50" value="" required="" id="id_last_name" placeholder="Фамилия…"></textarea>
<textarea class="cafe-text-field js-order-email-field cafe-block" rows="1" type="email" name="email" maxlength="254" value="" required="" id="id_email" placeholder="email…"></textarea>
<select name="select" rows="1" name="howdelivery" maxlength="50" required="" id="id_howdelivery" size="2" label="Способ доставки:">
<option value="" disabled selected>Способ доставки</option>
<option name="howdelivery" maxlength="50" required="" id="id_howdelivery" value="Самовывоз">Самовывоз</option>
<option name="howdelivery" maxlength="50" required="" id="id_howdelivery" value="Курьер">Курьер</option>
</select>
<textarea class="cafe-text-field js-order-address-field cafe-block" rows="2" type="text" name="address" maxlength="250" value="" required="" id="id_address" placeholder="Адрес…"></textarea>
<input class="cafe-text-field js-order-ddate-field cafe-block" rows="1" type="date" name="ddate" value="" required="" id="id_ddate" placeholder="Дата доставки">
<input class="cafe-text-field js-order-ddate-field cafe-block" rows="1" type="time" name="dtime" value="" required="" id="id_dtime" placeholder="Время доставки">
<textarea class="cafe-text-field js-order-ddate-field cafe-block" rows="1" id="checkout-mess" name="comment" maxlength="256" id="id_comment" placeholder="Комментарий..."></textarea>
<div class="cafe-text-field-hint">
Вы можете указать детали заказа, информацию для курьера и т.д.
<input type="submit" class="btn theme-btn">Оформить заказ</input>
</div>
</form>
</div>
Часть файла JavaScript к ней:
getOrderItem: function(itemEl) {
var id = itemEl.data('item-id');
return $('.js-order-item').filter(function() {
return ($(this).data('item-id') == id);
});
},
getOrderData: function() {
var order_data = [];
$('.js-item').each(function() {
var itemEl = $(this)
var id = itemEl.data('item-id');
var count = +itemEl.data('item-count') || 0;
if (count > 0) {
order_data.push({id: id, count: count});
}
});
return JSON.stringify(order_data);
},