Как вывести из бд данные на все страницы проекта python django
По сути мне нужно метод shop встроить в класс ProductListView Потому что вывод из метода shop выводит только на странице cart
class ProductsListView(ListView):
model = Product
template_name = 'shop/shop.html'
def shop(request):
cart = Order.get_cart(request.user)
items = cart.orderitem_set.all()
context = {
'cart': cart,
'items': items,
}
return render(request, 'shop/shop.html', context)
urls.py
path('', views.ProductsListView.as_view(), name='shop'),
path('cart_view/', views.cart_view, name='cart_view'),
path('detail/<int:pk>/', views.ProductsDetailView.as_view(), name='shop_detail'),
path('delete_item/<int:pk>', views.CartDeleteItem.as_view(), name='cart_delete_item'),
path('add-item-to-cart/<int:pk>', views.add_item_to_cart, name='add_item_to_cart'),
Согласно документации, вы можете переопределить метод get_context_data()
:
Пример из документации:
from django.utils import timezone
from django.views.generic.list import ListView
from articles.models import Article
class ArticleListView(ListView):
model = Article
paginate_by = 100 # if pagination is desired
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['now'] = timezone.now()
return context
В вашем случае это может быть так:
class ProductsListView(ListView):
model = Product
template_name = 'shop/shop.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
cart = Order.get_cart(self.request.user)
items = cart.orderitem_set.all()
context.update({
'cart': cart,
'items': items,
})
return context