Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create views.py #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from .models import Product

# Create your views here.
def index(request):
# return HttpResponse('Hello World')
products = Product.objects.all()
return render(request, 'index.html', {'products': products})

def new(request):
return HttpResponse('Welcome to PyShop New Arrivals')

def add_to_cart(request, product_id):
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
cart = request.session.get('cart', {})
cart[product_id] = cart.get(product_id, 0) + 1 # Increment quantity
request.session['cart'] = cart
return JsonResponse({'success': True, 'message': 'Product added to cart'})
else:
return redirect('index') # Redirect to index if not an AJAX request

def cart(request):
cart = request.session.get('cart', {})
cart_items = []

for product_id, quantity in cart.items():
try:
product = Product.objects.get(id=product_id)
cart_items.append({
'product': product,
'quantity': quantity,
'total_price': product.price * quantity
})
except Product.DoesNotExist:
pass

# Calculate the total amount for the cart
total_amount = sum(item['total_price'] for item in cart_items)

# Corrected render function with the context dictionary
return render(request, 'cart.html', {
'cart_items': cart_items,
'total_amount': total_amount
})