Мне нужно передать html
(мини-шаблон) со списком цен на мой шаблон: shop/medidas-cantidades.html
.
Цены представляют собой динамические значения, которые запрашиваются каждый раз, когда пользователь изменяет размер продукта, выбирая другую радиокнопку.
![enter image description here](https://i.stack.imgur.com/6IXG1.png)
Это запрос, который я сделаю, чтобы получить цены:
def prices(request):
size_selected = request.GET.get("size_selected")
prices = list(costo_de_los_productos.objects.filter(category=Category.objects.get(slug='c_slug'),
product=Product.objects.get(slug='product_slug'),
size=size_selected).values_list("price",flat=True))
return render(request, "shop/prices.html", {"prices": prices})
Теперь я отправляю эти данные в шаблон под названием shop / Prices.html., используя этот URL:
path('prices/', views.get_prices, name='prices')
где я:
{% for price in prices %}
<span>{{price}}</span>
{% endfor %}
В shop/medidas-cantidades.html
У меня есть это, чтобы узнать, какой переключатель выбран, и отправить это значениебэкэнд-функция prices(request):
function get_prices() {
return new Promise(function (resolve, reject) {
var size_selected = $('input[name=size]:checked').val();
$.ajax({
url: "/prices/",
data: { // Pass parameters in separate object
size_selected: size_selected
},
}).done(function (result) {
$('input[name=size]:checked').html(result);
resolve(result)
});
});
}
$("document").ready(function () {
$('input[name=size]').change(async /* <--- */ function () {
await /* <--- */ get_prices();
});
});
Я использую FormView для отображения моего основного html shop/medidas-cantidades.html
:
class StepOneView(FormView):
form_class = StepOneForm
template_name = 'shop/medidas-cantidades.html'
success_url = 'subir-arte'
def get_initial(self):
# pre-populate form if someone goes back and forth between forms
initial = super(StepOneView, self).get_initial()
initial['size'] = self.request.session.get('size', None)
initial['quantity'] = self.request.session.get('quantity', None)
initial['product'] = Product.objects.get(
category__slug=self.kwargs['c_slug'],
slug=self.kwargs['product_slug']
)
return initial
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['product'] = Product.objects.get(
category__slug=self.kwargs['c_slug'],
slug=self.kwargs['product_slug']
)
return context
def form_invalid(self, form):
print('Step one: form is NOT valid')
def form_valid(self, form):
cart_id = self.request.COOKIES.get('cart_id')
if not cart_id:
cart = Cart.objects.create(cart_id="Random")
cart_id = cart.id
cart = Cart.objects.get(id=cart_id)
item = CartItem.objects.create(
size=form.cleaned_data.get('size'),
quantity=form.cleaned_data.get('quantity'),
product=Product.objects.get(
category__slug=self.kwargs['c_slug'],
slug=self.kwargs['product_slug']
),
cart=cart
)
response = HttpResponseRedirect(self.get_success_url())
response.set_cookie("cart_id", cart_id)
response.set_cookie("item_id", item.id)
return response
shop / medidas-y-cantidades.html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-5">
<h2 class="text-center">{{ product.name }}</h2>
<p class="text-center">
<a class=""><i class="gold-star fas fa-star"></i></a>
<a class=""><i class="gold-star fas fa-star"></i></a>
<a class=""><i class="gold-star fas fa-star"></i></a>
<a class=""><i class="gold-star fas fa-star"></i></a>
<a class=""><i class="gold-star fas fa-star-half-alt"></i></a>
858 reviews
</p>
</div>
</div>
<div class="col-md-1"></div>
<div class="col-md-4 col-xs-12">
<div class="semi-transparent padded rounded">
<div class="bg-white rounded padded padded-40">
<form method="post">
{% csrf_token %}
<div class="">
<div id="size">
<legend class="text-size16 bold-font"> {{ form.size.label }}</legend>
<ul class="form-items">
<li>
<span>
{{ form.size.0.tag }}
{{ form.size.0.choice_label }}
</span>
</li>
<li>
<span>
{{ form.size.1.tag }}
{{ form.size.1.choice_label }}
</span>
</li>
<li>
<span>
{{ form.size.2.tag }}
{{ form.size.2.choice_label }}
</span>
</li>
<li>
<span>
{{ form.size.3.tag }}
{{ form.size.3.choice_label }}
</span>
</li>
</ul>
</div>
<div id="quantity">
<legend class="text-size16 bold-font"> {{ form.quantity.label }}</legend>
<ul class="form-items">
<li>
<span>
{{ form.quantity.0.tag }}
{{ form.quantity.0.choice_label }}
</span>
<span name="price" class="price_50_units">S/ {{ price_50_units }}</span>
<span class="savings savings_50"></span>
</li>
<li>
<span>
{{ form.quantity.1.tag }}
{{ form.quantity.1.choice_label }}
</span>
<span name="price"
class="price_100_units">S/ {{ price_100_units }}</span>
<span class="savings savings_100"></span>
</li>
<li>
<span>
{{ form.quantity.2.tag }}
{{ form.quantity.2.choice_label }}
</span>
<span name="price" class="price_200_units"></span>
<span class="savings savings_200"></span>
</li>
<li>
<span>
{{ form.quantity.3.tag }}
{{ form.quantity.3.choice_label }}
</span>
<span name="price" class="price_300_units"></span>
<span class="savings savings_300"></span>
</li>
<li>
<span>
{{ form.quantity.4.tag }}
{{ form.quantity.4.choice_label }}
</span>
<span name="price" class="price_500_units"></span>
<span class="savings savings_500"></span>
</li>
<li>
<span>
{{ form.quantity.5.tag }}
{{ form.quantity.5.choice_label }}
</span>
<span name="price" class="price_1000_units"></span>
<span class="savings savings_1000"></span>
</li>
</ul>
</div>
</div>
<button type="submit" class="btn btn-naranja text-white btn-block">Continuar
</button>
{# <a href="#" class="btn btn-naranja text-white btn-block">Continuar#}
</a>
<br>
<br>
<p class="text-size10 text-center">Siguiente: subir imagen</p>
</form>
</div>
</div>
</div>
<div class="col-md-1"></div>
</div>