Contents

0. Project Structure 1. Database 2. Django Views 3. JavaScript API 4. Django Templates 5. Testing 6. Complete Data Flow

Back

Fullstack Django Example - Burger Shop

From Database to Frontend with JS and Django Templates

0️⃣ Project Structure → Files & Folders

Before diving into Django models and views, here’s how the project is structured:

        burger_shop/               # Main project folder (created by django-admin)
        │
        ├── burger_shop/             # Django project settings
        │   ├── __init__.py
        │   ├── settings.py          # Database, installed apps, middleware, etc.
        │   ├── urls.py              # Project-level URL routing
        │   ├── asgi.py
        │   └── wsgi.py
        │
        ├── shop/                    # Our app (burgers, cart, etc.)
        │   ├── __init__.py
        │   ├── models.py            # Django models (Burger, CartItem)
        │   ├── views.py             # API and page views
        │   ├── urls.py              # App-level routes (included in project urls.py)
        │   ├── templates/           # Django templates
        │   │   └── shop/
        │   │       └── index.html
        │   └── static/              # JS, CSS, images
        │       ├── js/
        │       └── css/
        │
        ├── db.sqlite3               # Default database (or PostgreSQL/MySQL if configured)
        ├── manage.py                # Django’s CLI tool
        └── requirements.txt         # Python dependencies
          

This structure separates project settings (burger_shop) from the app logic (shop), keeping models, views, templates, and static assets well organized.

1️⃣ Database → Models (Python / Django)

We define the tables for burgers and cart items using Django models:

        # Django model for burgers
        from django.db import models
        
        class Burger(models.Model):
            name = models.CharField(max_length=120)
            price = models.DecimalField(max_digits=6, decimal_places=2)
        
            def to_dict(self):
                return {
                    'id': self.id,
                    'name': self.name,
                    'price': float(self.price)
                }
              

2️⃣ Django Views → JSON API

Example view to return all burgers as JSON:

        from django.http import JsonResponse
        from .models import Burger
        
        def burger_list(request):
            burgers = [b.to_dict() for b in Burger.objects.all()]
            return JsonResponse(burgers, safe=False)
          

Don't forget to add the URL in urls.py:

        from django.urls import path
        from . import views
        
        urlpatterns = [
            path('burgers/api/', views.burger_list, name='burger_list'),
        ]
          

Django receives the GET request via this URL, queries the database, and returns JSON.

3️⃣ JavaScript → API Consumption

Example function to add items to the cart:

        async function addToCart(burgerId, qty = 1) {
          const res = await fetch('/cart/api', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({burger_id: burgerId, quantity: qty})
          });
          return res.json();
        }
              

4️⃣ Django Templates → Initial Render

Template example using Django to display burgers:

        <ul id="catalog">
          {% for b in burgers %}
            <li>
              <strong>{{ b.name }}</strong> — ${{ b.price }}
              <button class="add-to-cart" data-id={{ b.id }}>Add</button>
            </li>
          {% endfor %}
        </ul>
              

5️⃣ Testing → Python & JS

Example of testing Python model and JS function:

        # Python test for Burger model
        def test_burger_to_dict():
            b = Burger(name='Cheese', price=5.99)
            assert b.to_dict() == {'id': None, 'name': 'Cheese', 'price': 5.99}
        
        // JS test for addToCart function
        async function testAddToCart() {
          res = await addToCart(1, 2);
          console.log('Cart response:', res);
        }
              

6️⃣ Complete Data Flow

Layer Example Purpose
Database burgers table Stores burger items and cart entries
Python Models Burger.objects.all() Queries DB and converts rows to Python objects
Django Views /burgers/api Handles JSON API & cart actions
Frontend JS fetch('/cart/api') Sends requests and updates UI dynamically
Django Templates {{ '{{ b.name }}' }} Renders initial data and action buttons
Testing Python: test_burger_to_dict()
JS: testAddToCart()
Ensures backend & frontend logic works