Экземпляры модели не отображаются в шаблоне
Заказы и OrderItems успешно добавляются в таблицу, но товары не отображаются в шаблоне. Если я использую print(order_item.objects.all()), то возникает ошибка :
AttributeError: Manager isn't accessible via OrderItem instances.
В базе данных django-admin товары красиво добавляются и удаляются из корзины. В настоящее время это товары моего заказа:
Order item
3 of Saregama Carvaan Earphones GX01 with Mic
5 of JBL Flip 5
3 of Puma Unisex-Adult BMW MMS R-cat Mid Sneaker
4 of Adidas Men's Astound M Running Shoe
4 order items
Эти позиции заказа получены от пользователя admin.
html:
{% block content %}
<main>
<div class="container">
<div class="table-responsive text-nowrap">
<h2>Order Summary</h2>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Item title</th>
<th scope="col">Price(₹)</th>
<th scope="col">Quantity</th>
<th scope="col">Total Item Price</th>
</tr>
</thead>
<tbody>
{% for order_item in order.items.all %}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td>{{ order_item.item.product_title }}</td>
<td>₹{{ order_item.item.sale_price }}</td>
<td>
<a href="{% url 'remove-single-item-from-cart' order_item.item.slug %}"><i class="fas fa-minus mr-2"></i></a>
{{ order_item.quantity }}
<a href="{% url 'add-to-cart' order_item.item.slug %}"><i class="fas fa-plus ml-2"></i></a>
</td>
<td>
{% if order_item.item.discount %}
₹{{ order_item.get_total_discount_item_price }}
<span class="badge badge-primary">Saving ₹{{ order_item.get_amount_saved }}</span>
{% else %}
₹{{ order_item.get_total_item_price }}
{% endif %}
<a style='color: red;' href="{% url 'remove-from-cart' order_item.item.slug %}">
<i class="fas fa-trash float-right"></i>
</a>
</td>
</tr>
{% empty %}
<tr>
<td colspan='5'>Your cart is empty</td>
</tr>
<tr>
<td colspan="5">
<a class='btn btn-primary float-right' href="{% url 'productdetails' %}">Continue shopping</a>
</td>
</tr>
{% endfor %}
{% if object.get_total %}
<tr>
<td colspan="4"><b>Order Total</b></td>
<td><b>₹{{ object.get_total }}</b></td>
</tr>
<tr>
<td colspan="5">
<a class='btn btn-warning float-right ml-2' href="">Proceed to checkout</a>
<a class='btn btn-primary float-right' href="">Continue shopping</a>
</td>
</tr>
{% endif %}
</tbody>
</table>
</div>
</div>
</main>
{% endblock content %}
модели:
class OrderItem(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
item = models.ForeignKey(AffProduct, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
objects = models.Manager()
def __str__(self):
return f"{self.quantity} of {self.item.product_title}"
def get_total_item_price(self):
return self.quantity * self.item.sale_price
def get_total_discount_item_price(self):
return self.quantity * (self.item.discount / Decimal('100'))
def get_amount_saved(self):
return self.get_total_item_price() - self.get_total_discount_item_price()
def get_final_price(self):
if self.item.discount_price:
return self.get_total_discount_item_price()
return self.get_total_item_price()
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
objects = models.Manager()
def __str__(self):
return self.user.username
def get_total(self):
total = 0
for order_item in self.items.all():
total += order_item.get_final_price()
return total
просмотров:
@login_required
def add_to_cart(request, slug):
item = get_object_or_404(AffProduct, slug=slug)
order_item, created = OrderItem.objects.get_or_create(
item=item,
user=request.user,
ordered=False
)
order_qs = Order.objects.filter(user=request.user, ordered=False)
if order_qs.exists():
order = order_qs[0]
# check if the order item is in the order
if order.items.filter(item__slug=item.slug).exists():
order_item.quantity += 1
order_item.save()
messages.info(request, "This item quantity was updated.")
print(order_item)
return redirect("cart")
else:
order.items.add(order_item)
messages.info(request, "This item was added to your cart.")
print(order_item)
return redirect("cart")
else:
ordered_date = timezone.now()
order = Order.objects.create(
user=request.user, ordered_date=ordered_date)
order.items.add(order_item)
messages.info(request, "This item was added to your cart.")
print(order_item)
return redirect("cart")
Попробуйте это:
@login_required
def add_to_cart(request, slug):
item = get_object_or_404(AffProduct, slug=slug)
order_item, created = OrderItem.objects.get_or_create(
item=item,
user=request.user,
ordered=False
)
order = Order.objects.filter(user=request.user, ordered=False).first()
if order:
# check if the order item is in the order
if order.items.filter(item__slug=item.slug).exists():
order_item.quantity += 1
order_item.save()
messages.info(request, "This item quantity was updated.")
else:
order.items.add(order_item)
messages.info(request, "This item was added to your cart.")
else:
ordered_date = timezone.now()
order = Order.objects.create(
user=request.user, ordered_date=ordered_date)
order.items.add(order_item)
messages.info(request, "This item was added to your cart.")
return render(request, '<template-name>', {'order_item': order_item, 'object': order})
И print(order_item.objects.all())
-> print(OrderItem.objects.all())