Здравствуйте. Подскажите, как отобразить историю заказов в профиле конкретного пользователя.
Приложение "Orders"
models.py
from django.db import models
import django
from shop.models import Product
from django.contrib.auth.models import User
class Order(models.Model):
user_id = models.ForeignKey(User,on_delete=models.PROTECT, related_name='orders', verbose_name="Заказы")
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
postal_code = models.CharField(max_length=20)
city = models.CharField(max_length=100)
street = models.CharField(max_length=100, default="s")
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
class Meta:
ordering = ('-created',)
verbose_name = 'Заказ'
verbose_name_plural = 'Заказы'
def __str__(self):
return 'Order {}'.format(self.id)
def get_total_cost(self):
return sum(item.get_cost() for item in self.items.all())
class OrderItem(models.Model):
order = models.ForeignKey(Order, related_name='items')
product = models.ForeignKey(Product, related_name='order_items')
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField(default=1)
def __str__(self):
return '{}'.format(self.id)
def get_cost(self):
return self.price * self.quantity
views.py
from django.shortcuts import render
from .models import OrderItem
from .forms import OrderCreateForm
from cart.cart import Cart
def order_create(request):
cart = Cart(request)
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save()
for item in cart:
OrderItem.objects.create(order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity'])
# очистка корзины
cart.clear()
return render(request, 'orders/order/created.html',
{'order': order})
else:
form = OrderCreateForm
return render(request, 'orders/order/create.html',
{'cart': cart, 'form': form})
def my_orders(request):
products = Product.objects.all()
**************************myorders = Order.objects.filter(user_id=request.user)*****************************
product_ordered = OrderItem.objects.all()
assert isinstance(request, HttpRequest)
return render(
request,
'app/my_orders.html', {'products': products, 'product_ordered': product_ordered, 'myorders': myorders,}
)
html
...
{% for item in myorders %} {{ item }} {% endfor %}
...
В шаблоне HTML пусто, ничего не выводится.