So I am working on a Django mock website similar to restoplus, where restaurants can fill in their name, image, details, menus, sides, toppings, pick their brand colours (primary colours and secondary colours) and it will generate a standard landing page for that restaurant using the brand colours and details and menus.
Now the problem is I am trying to update the price in real time using js depending on what the user selects. But it’s not working. Also the quantity + – buttons are also not working. Now for that I have tried to use debug statements but even when I click on the buttons or select a menuitem option, neither the price gets updated not the quantity, and the console is clear, nothing appears on the console. Why is this? Can anyone help me out here? Thanks!
My models.py:
from django.db import models
from django.contrib.auth.models import User
from django.utils.text import slugify
class Restaurant(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
image = models.ImageField(upload_to='restaurant_images/')
banner_image = models.ImageField(upload_to='restaurant_images/', null=True)
primary_color = models.CharField(max_length=7) # Hex color code
secondary_color = models.CharField(max_length=7) # Hex color code
favicon = models.FileField(upload_to='restaurant_favicons/', null=True, blank=True)
slug = models.SlugField(unique=True, max_length=100, null=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super().save(*args, **kwargs)
def __str__(self):
return self.name
class Menu(models.Model):
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, related_name='menus')
name = models.CharField(max_length=50)
def __str__(self):
return f'{self.restaurant} {self.name} Menu'
class Topping(models.Model):
menu = models.ForeignKey(Menu, on_delete=models.CASCADE, related_name='toppings')
name = models.CharField(max_length=50)
price = models.DecimalField(max_digits=4, decimal_places=2)
def __str__(self):
return f'{self.menu} - {self.name}'
class Side(models.Model):
menu = models.ForeignKey(Menu, on_delete=models.CASCADE, related_name='sides')
name = models.CharField(max_length=50)
price = models.DecimalField(max_digits=4, decimal_places=2)
def __str__(self):
return f'{self.menu} - {self.name}'
class Addon(models.Model):
menu = models.ForeignKey(Menu, on_delete=models.CASCADE, related_name='addons')
name = models.CharField(max_length=50)
price = models.DecimalField(max_digits=4, decimal_places=2)
def __str__(self):
return f'{self.menu} - {self.name}'
class Drink(models.Model):
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, related_name='drinks')
name = models.CharField(max_length=50)
price = models.DecimalField(max_digits=4, decimal_places=2)
def __str__(self):
return f'{self.restaurant} - {self.name}'
class MenuItem(models.Model):
menu = models.ForeignKey(Menu, on_delete=models.CASCADE, related_name='menu_items')
name = models.CharField(max_length=100)
description = models.TextField()
image = models.ImageField(upload_to='menu_item_images/', blank=True, null=True)
def __str__(self):
return f'{self.menu.restaurant.name} {self.menu.name} Menu - {self.name}'
class MenuItemOption(models.Model):
menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, related_name='options')
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return f'{self.menu_item} - {self.name}'
class MenuItemSize(models.Model):
menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, related_name='sizes')
name = models.CharField(max_length=50) # e.g., "Small", "Medium", "Large"
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return f'{self.menu_item} - {self.name}'
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
total_price = models.DecimalField(max_digits=8, decimal_places=2)
STATUS_CHOICES = [
('pending', 'Pending'),
('processing', 'Processing'),
('completed', 'Completed'),
('cancelled', 'Cancelled'),
]
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE)
menu_item_option = models.ForeignKey(MenuItemOption, on_delete=models.SET_NULL, null=True, blank=True)
menu_item_size = models.ForeignKey(MenuItemSize, on_delete=models.SET_NULL, null=True, blank=True)
quantity = models.IntegerField(default=1)
toppings = models.ManyToManyField(Topping, blank=True)
sides = models.ManyToManyField(Side, blank=True)
addons = models.ManyToManyField(Addon, blank=True)
My views.py:
from django.shortcuts import render
from django.shortcuts import render, get_object_or_404
from .models import Restaurant, MenuItem, MenuItemOption, MenuItemSize, Addon, Drink, Topping
from django.db.models import Min, Exists, OuterRef
from django.db.models.functions import Coalesce
from django.template.loader import render_to_string
from django.http import HttpResponse
def home(request):
return render(request, "restaurant/index.html")
def restaurant_landing_page(request, restaurant_slug):
restaurant = get_object_or_404(Restaurant, slug=restaurant_slug)
menu_items = MenuItem.objects.filter(menu__restaurant=restaurant).annotate(
has_options=Exists(MenuItemOption.objects.filter(menu_item=OuterRef('pk'))),
has_sizes=Exists(MenuItemSize.objects.filter(menu_item=OuterRef('pk'))),
lowest_price=Min(
Coalesce('options__price', 'sizes__price')
)
)
context = {
'restaurant': restaurant,
'menu_items': menu_items,
}
return render(request, 'restaurant/restaurant_landing_page.html', context)
def get_menu_item_details(request, item_id):
item = get_object_or_404(MenuItem, id=item_id)
restaurant = item.menu.restaurant
options = item.options.all()
sizes = item.sizes.all()
sides = item.menu.sides.all()
addons = item.menu.addons.all()
drinks = restaurant.drinks.all()
toppings = item.menu.toppings.all()
context = {
'restaurant': restaurant,
'item': item,
'options': options,
'sizes': sizes,
'sides': sides,
'addons': addons,
'drinks': drinks,
'toppings': toppings,
}
html = render_to_string('restaurant/menu_item_modal.html', context)
return HttpResponse(html)
My restaurant_landing_page.html:
<!-- restaurant_landing_page.html -->
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ restaurant.name }}</title>
{% if restaurant.favicon %}
<link rel="icon" type="image/x-icon" href="{{ restaurant.favicon.url }}">
{% endif %}
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
<style>
:root {
--primary-color: {{ restaurant.primary_color }};
--secondary-color: {{ restaurant.secondary_color }};
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Poppins', sans-serif;
line-height: 1.6;
color: #333;
background-color: #f8f8f8;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
}
header {
background-color: var(--primary-color);
color: white;
padding: 20px 0;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
nav {
display: flex;
justify-content: space-between;
align-items: center;
}
.logo img {
height: 50px;
width: auto;
}
nav ul {
display: flex;
list-style-type: none;
}
nav ul li {
margin-left: 20px;
}
nav ul li a {
color: white;
text-decoration: none;
font-weight: 600;
transition: opacity 0.3s ease;
}
nav ul li a:hover {
opacity: 0.8;
}
.hero {
background-image: url('{{ restaurant.banner_image.url }}');
background-size: cover;
background-position: center;
padding: 120px 0;
position: relative;
}
.hero::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
}
.hero-content {
position: relative;
z-index: 1;
color: white;
text-align: center;
}
.hero-content h1 {
font-size: 3.5rem;
margin-bottom: 20px;
text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
}
.hero-content p {
font-size: 1.2rem;
margin-bottom: 30px;
max-width: 600px;
margin-left: auto;
margin-right: auto;
}
.cta-button {
display: inline-block;
background-color: var(--primary-color);
color: white;
padding: 12px 24px;
text-decoration: none;
border-radius: 5px;
font-weight: 600;
transition: background-color 0.3s ease, transform 0.3s ease;
}
.cta-button:hover {
background-color: var(--secondary-color);
color: black;
transform: translateY(-3px);
}
.menu-section {
padding: 60px 0;
background-color: #f9f9f9;
}
.menu-section h2 {
text-align: center;
font-size: 2.5rem;
margin-bottom: 40px;
color: var(--primary-color);
}
.menu-category h3 {
font-size: 1.8rem;
color: var(--primary-color);
margin-bottom: 20px;
border-bottom: 2px solid var(--primary-color);
padding-bottom: 10px;
}
.menu-item .price {
display: block;
font-weight: 600;
color: var(--primary-color);
font-size: 1rem;
}
.menu-category {
margin-bottom: 40px;
}
.menu-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
}
.menu-item {
background-color: white;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.menu-item:hover {
transform: translateY(-5px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}
.menu-item-image {
height: 120px;
background-size: cover;
background-position: center;
}
.menu-item-content {
padding: 15px;
}
.menu-item h4 {
margin: 0 0 10px 0;
font-size: 1.1rem;
color: var(--primary-color);
}
.menu-item .description {
font-size: 0.9rem;
color: #666;
margin-bottom: 10px;
line-height: 1.4;
}
@media (max-width: 768px) {
.menu-grid {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}
}
footer {
background-color: var(--primary-color);
color: white;
text-align: center;
padding: 20px 0;
margin-top: 80px;
}
@media (max-width: 768px) {
.hero-content h1 {
font-size: 2.5rem;
}
.hero-content p {
font-size: 1rem;
}
.menu-grid {
grid-template-columns: 1fr;
}
}
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
max-width: 600px;
border-radius: 8px;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<header>
<div class="container">
<nav>
<div class="logo">
<img src="{{ restaurant.image.url }}" alt="{{ restaurant.name }} logo">
</div>
<ul>
<li><a href="#menu">Menu</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</div>
</header>
<main>
<section class="hero">
<div class="container">
<div class="hero-content">
<h1>{{ restaurant.name }}</h1>
<p>{{ restaurant.description }}</p>
<a href="#menu" class="cta-button">View Menu</a>
</div>
</div>
</section>
<section id="menu" class="menu-section">
<div class="container">
<h2>Our Menu</h2>
{% regroup menu_items by menu as menu_list %}
{% for menu in menu_list %}
<div class="menu-category">
<h3>{{ menu.grouper.name }}</h3>
<div class="menu-grid">
{% for item in menu.list %}
<div class="menu-item" data-item-id="{{ item.id }}">
{% if item.image %}
<div class="menu-item-image" style="background-image: url('{{ item.image.url }}')"></div>
{% endif %}
<div class="menu-item-content">
<h4>{{ item.name }}</h4>
<p class="description">{{ item.description|truncatewords:10 }}</p>
{% if item.has_options or item.has_sizes %}
{% if item.lowest_price %}
<span class="price">From ${{ item.lowest_price|floatformat:2 }}</span>
{% else %}
<span class="price">Price varies</span>
{% endif %}
{% else %}
<span class="price">See details</span>
{% endif %}
</div>
</div>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
</section>
</main>
<footer>
<div class="container">
<p>© {% now "Y" %} {{ restaurant.name }}. All rights reserved.</p>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// Smooth scrolling for anchor links
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top
}, 500, 'linear');
});
// Modal functionality
var modal = $("#menuItemModal");
var span = $(".close");
$(".menu-item").on("click", function() {
var itemId = $(this).data("item-id");
$.ajax({
url: /get-menu-item-details/${itemId}/, // You'll need to create this view
type: "GET",
success: function(response) {
$("#modalContent").html(response);
modal.css("display", "block");
},
error: function(xhr, status, error) {
console.error("Error fetching menu item details:", error);
}
});
});
span.on("click", function() {
modal.css("display", "none");
});
$(window).on("click", function(event) {
if (event.target == modal[0]) {
modal.css("display", "none");
}
});
});
</script>
<div id="menuItemModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<div id="modalContent"></div>
</div>
</div>
</body>
</html>
My menu_item_modal.html:
<div class="modal-item-details" style="color: {{ restaurant.primary_color }};">
{% if item.image %}
<img src="{{ item.image.url }}" alt="{{ item.name }}" class="modal-item-image">
{% endif %}
<h2>{{ item.name }}</h2>
<p>{{ item.description }}</p>
<form id="orderForm">
{% if options %}
<div class="selection-section">
<h3>Select From</h3>
<span class="selection-limit">Select 1</span>
<hr>
{% for option in options %}
<div class="selection-item">
<input type="radio" id="option{{ option.id }}" name="option" value="{{ option.id }}" data-price="{{ option.price }}">
<label for="option{{ option.id }}">{{ option.name }}</label>
<span class="price">${{ option.price|floatformat:2 }}</span>
</div>
{% endfor %}
</div>
{% endif %}
{% if sizes %}
<div class="selection-section">
<h3>Sizes</h3>
<hr>
{% for size in sizes %}
<div class="selection-item">
<input type="radio" id="size{{ size.id }}" name="size" value="{{ size.id }}" data-price="{{ size.price }}">
<label for="size{{ size.id }}">{{ size.name }}</label>
<span class="price">${{ size.price|floatformat:2 }}</span>
</div>
{% endfor %}
</div>
{% endif %}
{% if addons %}
<div class="selection-section">
<h3>Add-ons</h3>
<hr>
{% for addon in addons %}
<div class="selection-item">
<input type="checkbox" id="addon{{ addon.id }}" name="addons" value="{{ addon.id }}" data-price="{{ addon.price }}">
<label for="addon{{ addon.id }}">{{ addon.name }}</label>
<span class="price">${{ addon.price|floatformat:2 }}</span>
</div>
{% endfor %}
</div>
{% endif %}
{% if sides %}
<div class="selection-section">
<h3>Sides</h3>
<hr>
{% for side in sides %}
<div class="selection-item">
<input type="checkbox" id="side{{ side.id }}" name="sides" value="{{ side.id }}" data-price="{{ side.price }}">
<label for="side{{ side.id }}">{{ side.name }}</label>
<span class="price">${{ side.price|floatformat:2 }}</span>
</div>
{% endfor %}
</div>
{% endif %}
{% if drinks %}
<div class="selection-section">
<h3>Drinks</h3>
<hr>
{% for drink in drinks %}
<div class="selection-item">
<input type="radio" id="drink{{ drink.id }}" name="drink" value="{{ drink.id }}" data-price="{{ drink.price }}">
<label for="drink{{ drink.id }}">{{ drink.name }}</label>
<span class="price">${{ drink.price|floatformat:2 }}</span>
</div>
{% endfor %}
</div>
{% endif %}
{% if toppings %}
<div class="selection-section">
<h3>Toppings</h3>
<hr>
{% for topping in toppings %}
<div class="selection-item">
<input type="checkbox" id="topping{{ topping.id }}" name="toppings" value="{{ topping.id }}" data-price="{{ topping.price }}">
<label for="topping{{ topping.id }}">{{ topping.name }}</label>
<span class="price">${{ topping.price|floatformat:2 }}</span>
</div>
{% endfor %}
</div>
{% endif %}
<div class="special-instructions">
<h3>Special Instructions</h3>
<textarea name="special_instructions" id="special-instructions" rows="3"></textarea>
</div>
<div class="quantity-section">
<h3>Quantity</h3>
<button type="button" class="quantity-btn" id="decrease">-</button>
<input type="number" id="quantity" name="quantity" value="1" min="1">
<button type="button" class="quantity-btn" id="increase">+</button>
</div>
<div class="total-price">
<h3>Total: $<span id="totalPrice">0.00</span></h3>
</div>
<div class="modal-actions">
<button type="button" id="cancelOrder" style="background-color: {{ restaurant.secondary_color }}; color: {{ restaurant.primary_color }};">Cancel</button>
<button type="submit" id="addToOrder" style="background-color: {{ restaurant.primary_color }}; color: {{ restaurant.secondary_color }};">Add to Order</button>
</div>
</form>
</div>
<style>
body {
font-family: 'Poppins', sans-serif;
background-color: #f0f0f0;
}
.modal-item-details {
color: {{ restaurant.primary_color }};
padding: 20px;
}
.modal-item-details h2, .modal-item-details h3 {
color: {{ restaurant.primary_color }};
margin-bottom: 10px;
}
.modal-item-image {
max-width: 100%;
height: auto;
border-radius: 8px;
margin-bottom: 20px;
}
.selection-section {
margin-bottom: 20px;
}
.selection-item {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.selection-item label {
flex-grow: 1;
margin-left: 10px;
}
.price {
font-weight: bold;
color: {{ restaurant.primary_color }};
}
.quantity-section {
display: flex;
align-items: center;
margin-bottom: 20px;
}
.quantity-btn {
background-color: {{ restaurant.primary_color }};
color: {{ restaurant.secondary_color }};
border: none;
padding: 5px 10px;
cursor: pointer;
border-radius: 4px;
}
#quantity {
width: 50px;
text-align: center;
margin: 0 10px;
padding: 5px;
border: 1px solid #e0e0e0;
border-radius: 4px;
}
.total-price {
font-size: 1.2em;
margin-bottom: 20px;
}
.modal-actions {
display: flex;
justify-content: space-between;
}
.modal-actions button {
padding: 10px 20px;
border: none;
cursor: pointer;
font-weight: bold;
border-radius: 4px;
}
.special-instructions textarea {
width: 100%;
padding: 10px;
border: 1px solid #e0e0e0;
border-radius: 4px;
resize: none;
}
hr {
border: none;
border-top: 1px solid #e0e0e0;
margin: 10px 0;
}
</style>
<!-- Place this script at the end of the body -->
<script>
document.addEventListener('DOMContentLoaded', function() {
const form = document.getElementById('orderForm');
const quantityInput = document.getElementById('quantity');
const totalPriceSpan = document.getElementById('totalPrice');
const decreaseBtn = document.getElementById('decrease');
const increaseBtn = document.getElementById('increase');
function updateTotalPrice() {
console.log("Updating total price...");
let total = 0;
const quantity = parseInt(quantityInput.value);
console.log("Quantity: ", quantity);
const selectedOption = form.querySelector('input[name="option"]:checked');
if (selectedOption) {
total += parseFloat(selectedOption.dataset.price);
console.log("Selected option price: ", selectedOption.dataset.price);
}
const selectedSize = form.querySelector('input[name="size"]:checked');
if (selectedSize) {
total += parseFloat(selectedSize.dataset.price);
console.log("Selected size price: ", selectedSize.dataset.price);
}
const selectedAddons = form.querySelectorAll('input[name="addons"]:checked');
selectedAddons.forEach(addon => {
total += parseFloat(addon.dataset.price);
console.log("Selected addon price: ", addon.dataset.price);
});
const selectedSides = form.querySelectorAll('input[name="sides"]:checked');
selectedSides.forEach(side => {
total += parseFloat(side.dataset.price);
console.log("Selected side price: ", side.dataset.price);
});
const selectedDrink = form.querySelector('input[name="drink"]:checked');
if (selectedDrink) {
total += parseFloat(selectedDrink.dataset.price);
console.log("Selected drink price: ", selectedDrink.dataset.price);
}
const selectedToppings = form.querySelectorAll('input[name="toppings"]:checked');
selectedToppings.forEach(topping => {
total += parseFloat(topping.dataset.price);
console.log("Selected topping price: ", topping.dataset.price);
});
total *= quantity;
totalPriceSpan.textContent = total.toFixed(2);
console.log("Total price: ", total.toFixed(2));
}
// Add event listeners to all form inputs
form.addEventListener('change', function() {
console.log("Form changed");
updateTotalPrice();
});
// Add event listener to quantity input
quantityInput.addEventListener('input', function() {
if (this.value < 1) this.value = 1;
console.log("Quantity input changed");
updateTotalPrice();
});
// Add event listeners to quantity buttons
decreaseBtn.addEventListener('click', function(e) {
e.preventDefault(); // Prevent form submission
console.log("Decrease button clicked");
if (quantityInput.value > 1) {
quantityInput.value = parseInt(quantityInput.value) - 1;
updateTotalPrice();
}
});
increaseBtn.addEventListener('click', function(e) {
e.preventDefault(); // Prevent form submission
console.log("Increase button clicked");
quantityInput.value = parseInt(quantityInput.value) + 1;
updateTotalPrice();
});
// Initial price update
updateTotalPrice();
});
</script>