Python

Django for Restaurants: Building a Kitchen Management Application

Pinterest LinkedIn Tumblr

Django Restaurant Menu App Tutorial

write for us technology

This article dives into creating a dynamic Django web application for displaying a restaurant menu. Users will be able to explore various meal categories, click on specific meals to access detailed information, and enjoy a visually appealing interface. We’ll assume you have a basic understanding of Django concepts like models, views, and templates, along with a pre-existing Django project with a meal model and admin setup.

This article will guide you through building a restaurant menu web app using Django, a popular Python web framework.

The App’s Functionality

The app caters to both restaurant owners and customers:

  • Customers: View the restaurant’s menu, including available and unavailable dishes. Unavailable items will be displayed in strikethrough text. Clicking on a menu item can lead to a detailed description page.
  • Restaurant Owners (Cooks): Access an admin interface to manage the menu. This includes adding new dishes with descriptions, prices, categories (starters, main course, etc.), and setting availability.

Benefits of Building this App

This project offers a valuable learning experience for anyone interested in Django development.

By building this app, you’ll gain a deeper understanding of:

  • Working with Django models and views
  • Creating a user interface (UI) with templates
  • Admin interface development
  • Implementing functionalities like displaying item availability and linking to detailed pages

A Look Ahead

The next part of the tutorial series will delve into using Python to generate a QR code. This QR code can be printed on menus or displayed elsewhere for customers to scan with their phones, directing them to the web app.

Beyond Restaurants

While this tutorial focuses on a restaurant menu, the core structure can be adapted to create other applications with clickable blocks that link to detailed content pages.

I hope this summary effectively conveys the key aspects of the Django restaurant menu app tutorial.

Generating a QR Code with Python for Django App

This article outlines the steps to create a QR code using Python that links to your Django web application.

Why Use Python for QR Codes?

While other tools exist, Python offers a convenient way to generate QR codes within your development environment.

Setting Up the Project

  • Create a new Python project to house both the QR code generation script (qr.py) and your Django application.
  • Activate your virtual environment (ensure it’s highlighted in parentheses).

Installing Required Libraries

Open your terminal and install the following libraries using pip:

qrcode: Generates QR codes

pillow: Image processing library (indirect dependency of qrcode)

Bash

pip install qrcode pillow

Creating the QR Code Script (qr.py)

Import the qrcode library.

Specify the URL you want the QR code to link to (replace 127.0.0.1:8000 with your actual URL when deploying).

Python

import qrcode

url = ‘127.0.0.1:8000’  # Replace with your Django app’s URL

Use qrcode.make(url) to create a QR code image object.

Save the image object as a PNG file using image.save(‘qr.png’).

Running the Script and Using the QR Code

  • Execute the script using python qr.py.
  • A QR code image named qr.png will be generated.
    • This code, when scanned with a mobile phone, will direct users to your Django app’s URL.
  • Provide this QR code to your client (the restaurant) for distribution to their customers.

Important Note:

  • Update the URL in the script to your deployed application’s domain name before generating the final QR code for customer use.

Setting Up a Django Restaurant Menu App

This article guides you through creating a Django project and app for a restaurant menu web application.

Prerequisites

  • Python installed
  • Familiarity with a terminal

Steps

  • Install Django:

Bash

pip install Django

  • Create a Django Project:

Bash

django-admin startproject Mysite

This creates a directory named Mysite containing Django project files.

  • Create a Django App:

Bash

python manage.py startapp restaurant_menu

This creates a directory named restaurant_menu within Mysite to house your app’s code.

  • Connect the App to the Project:
    • Open Mysite/settings.py.
    • Locate the INSTALLED_APPS list.
    • Add your app’s name (‘restaurant_menu’) within quotes and a comma after the last app.
    • Save the file.
  • Run the Project:

Bash

python manage.py runserver

This starts the development server and displays the default Django welcome page (http://127.0.0.1:8000/) in your browser.

Explanation

  • manage.py is a utility script used to manage your Django project.
  • INSTALLED_APPS specifies the apps that are part of your project.

Next Steps

In subsequent videos, you’ll configure URLs to display specific content within your app and build functionalities for the restaurant menu.

Building the Database Model for a Django Restaurant Menu App

This article details the steps involved in creating a database model for a Django restaurant menu application.

Understanding Database Models

  • Database models define the structure of your app’s data.
  • Each model represents a database table with specific fields (columns).

Setting Up the Model

  • Navigate to your app’s models.py file.
  • Create a class inheriting from models.Model:

Python

class Item(models.Model):

# … fields will be defined here

  • Define Database Fields:
    • Each field represents a column in the database table.
    • Use appropriate data types like CharField for text, DecimalField for numbers with decimals, and ForeignKey for relationships between tables.

Python

meal = models.CharField(max_length=1000, unique=True)

description = models.CharField(max_length=2000)

price = models.DecimalField(max_digits=10, decimal_places=2)

meal_type = models.CharField(max_length=20, choices=MEAL_TYPE)

# … other fields

  • Define Relationships (Optional):
    • Use ForeignKey to connect tables.
    • In this case, ForeignKey links the Item model to the Django user model (User).

Python

author = models.ForeignKey(User, on_delete=models.PROTECT)

  • Define Additional Fields (Optional):
    • Include fields like status (available/unavailable) and timestamps for creation and updates.
    • Use choices for finite sets of values.
    • Utilize auto_now_add and auto_now for automatic timestamp recording.

Python

status = models.IntegerField(choices=STATUS, default=0)

date_created = models.DateTimeField(auto_now_add=True)

date_updated = models.DateTimeField(auto_now=True)

  • Define the __str__() method (Optional):
    • This method specifies how the model instance is displayed in the admin interface.

Python

def __str__(self):

return self.meal

Creating the Database Table

  • Run python manage.py makemigrations to create migration files for the model changes.
  • Address any errors (e.g., missing field attributes).
  • Run python manage.py migrate to apply the migrations and create the database table.

Verifying the Database Structure

  • Use a database management tool like DB Browser for SQLite to view the database structure.
  • The restaurant_menu_item table should now exist with all the defined fields.

Next Steps

With the database model established, you can proceed to creating views for your app to handle user interactions and display data.

Building the Admin Interface for a Django Restaurant Menu App

This article guides you through creating an admin interface for your Django restaurant menu application.

Admin Interface: Purpose and Benefits

  • The admin interface allows authorized users (admins) to manage data within the app.
  • This includes adding, editing, and deleting data associated with the app’s models.

Steps to Create the Admin Interface

  1. Locate the admin.py file:

Navigate to your app’s directory (e.g., restaurant_menu).

  • Create the MenuItemAdmin class:

Inherit from admin.ModelAdmin.

Define the following within the class:

list_display: A tuple specifying fields to display on the admin interface (e.g., (‘meal’, ‘status’)).

list_filter: A tuple allowing filtering by specific fields (e.g., (‘status’,)).

search_fields: A tuple enabling searching by designated fields (e.g., (‘meal’, ‘description’)).

  • Register the Admin Class:

Use admin.site.register to associate the MenuItemAdmin class with the Item model from models.py.

Running the Admin Interface

  • Create a Superuser:
    • In your terminal (ensure virtual environment is activated), run python manage.py createsuperuser.
    • Provide a username, email, and password for the superuser account.
  • Start the Development Server:
    • Run python manage.py runserver to launch the development server.
  • Access the Admin Interface:
    • Visit http://127.0.0.1:8000/admin/ in your web browser.
    • Log in using the superuser credentials.

Utilizing the Admin Interface

  • You’ll see a list of all Item objects (meals) in the database.
  • Use the search and filter options to navigate the data.
  • Add new meals by clicking the “Add Item” button.
  • Edit existing meals or delete them as needed.

Verifying Data in the Database

  • Tools like DB Browser for SQLite can be used to view the database table (restaurant_menu_item) containing the meal data.

Next Steps

With the admin interface functional, you can now focus on displaying this data on the front-end of your web application.

Displaying Dynamic Restaurant Menu Data in a Django Template

This article guides you through displaying actual meal data from your Django restaurant menu app on the front-end.

Prerequisites

  • A functional Django app with a model for meals (Item) containing fields like meal, description, meal_type, and status.
  • An admin interface set up to add and manage meal data.

Steps

  • Modify index.html:
    • Remove Dummy Data: Replace the pre-defined meal data in index.html with an empty dictionary.
    • Import MEAL_TYPES: Import MEAL_TYPES from models.py to access meal category data.
    • Create Initial Context: Set the context dictionary to include MEAL_TYPES as a key-value pair.
  • Display Meal Categories:
    • Iterate Through MEAL_TYPES: Use a for loop to iterate through each meal category tuple in MEAL_TYPES.
    • Access and Display Category Names: Within the loop, access the second element of each tuple (index 1) to display the category name (e.g., “Starters”).
  • Display Meals by Category:
    • Access Items from Model: Use Item.objects.all() to retrieve all meal objects from the database.
    • Iterate Through Items: Implement a nested for loop to iterate through each meal object (item) in the retrieved list.
    • Apply Conditional Filtering: Inside the nested loop, use an if statement to check if the meal_type of the current item matches the current category being iterated through in the outer loop.
    • Display Meal Details: If the condition is met, display the meal’s name (item.meal) and description (item.description) within the appropriate category section on the webpage.
  • Handle Unavailable Meals (Optional):
    • Check Status: Use an if statement to check the status field of the current item.
    • Strikethrough Unavailable Meals: If the status is zero (unavailable), wrap the meal name in <del> tags to display it with a strikethrough effect.
    • Display Available Meals (Else Block): Implement an else block to display the meal name and description normally for available meals (status is one).
  • Convert Meals to Links (Optional):
    • Wrap Meal Names in Links: Modify the meal name display to use anchor tags (<a>) with appropriate URLs to link to detailed information pages for each meal.

Additional Considerations

  • Use proper indentation for readability.
  • Consider using CSS frameworks like Bootstrap for improved styling.

Creating Dynamic Restaurant Menus with Django

This article guides you through creating a functional Django web application that displays a restaurant menu with clickable links to detailed information for each meal.

Prerequisites:

  • A basic understanding of Django concepts like models, views, and templates.
  • A Django project with a model for meals (Item) containing fields like meal, description, meal_type, and status (availability).
  • An admin interface set up to manage meal data.

Steps:

  • Modify index.html:
    • Remove Static Meal Data: Replace pre-defined meal data in index.html with an empty dictionary.
    • Import MEAL_TYPES: Import MEAL_TYPES from models.py to access meal category data.
    • Create Initial Context: Set the context dictionary to include MEAL_TYPES as a key-value pair.
  • Display Meal Categories:
    • Iterate Through MEAL_TYPES: Use a for loop to iterate through each meal category tuple in MEAL_TYPES.
    • Access and Display Category Names: Within the loop, access the second element of each tuple (index 1) to display the category name (e.g., “Starters”).
  • Display Meals by Category:
    • Retrieve Items from Model: Use Item.objects.all() to retrieve all meal objects from the database.
    • Nested Loops for Filtering: Implement nested for loops:
      • Outer Loop: Iterates through retrieved items (item).
      • Inner Loop (Conditional): Checks if item.meal_type matches the current category being iterated through in the outer loop.
        • Display Meal Details (if Matched): Display the meal’s name (item.meal) and description (item.description) within the appropriate category section.
  • Handle Unavailable Meals (Optional):
    • Check Status: Use an if statement to check the status field of the current item.
    • Strikethrough Unavailable Meals: If the status is zero (unavailable), wrap the meal name in <del> tags for a strikethrough effect.
    • Display Available Meals (Else Block): Implement an else block to display the meal name and description normally for available meals (status is one).

Additional Considerations:

  • Use proper indentation for readability.
  • Consider using CSS frameworks like Bootstrap for improved styling.

Explanation of the Video Tutorial:

The video tutorial builds upon these steps, demonstrating how to:

  • Create Dynamic Links:
    • Use Django’s URL resolution within the href attribute of anchor tags.
    • Include the URL name defined in urls.py for the meal detail view.
    • Pass the meal’s primary key (item.pk) dynamically to the URL using string formatting.
  • Create Meal Detail View:
    • Define a view class to handle requests for individual meal pages.
    • Retrieve the meal object based on the primary key passed in the URL.
    • Render a template displaying the meal’s details (name, description, price, etc.).
  • Implement Base Template:
    • Create a base template containing a navigation menu structure.
    • Extend the base template from index.html and menu_item_detail.html for consistent layout.
  • Apply Bootstrap Styling:
    • Include Bootstrap CSS in the base template.
    • Apply Bootstrap classes to elements in index.html and menu_item_detail.html for visual design.

Summary Table: Creating Dynamic Restaurant Menus with Django

StepDescriptionPurpose
Modify index.htmlRemove static meal data. Import MEAL_TYPES and create initial context.Prepare the template for dynamic content.
Display Meal CategoriesIterate through MEAL_TYPES and display category names.Organize meals by category.
Display Meals by CategoryRetrieve all meals using Item.objects.all(). Use nested loops for filtering and displaying meals based on category.Display relevant meals under each category.
Handle Unavailable Meals (Optional)Check status field and apply strikethrough for unavailable meals.Indicate meal availability.
Convert Meals to LinksWrap meal names in anchor tags with dynamic URLs referencing the meal detail view.Allow users to navigate to individual meal pages.
Create Meal Detail View (Video Tutorial)Define a view to handle meal detail requests, retrieve the meal object, and render a template.Display detailed information for each meal.
Implement Base Template (Video Tutorial)Create a base template with navigation menu and extend it from other templates for consistent layout.Provide a structured layout across all pages.
Apply Bootstrap Styling (Video Tutorial)Include Bootstrap CSS and apply classes to elements for styling.Enhance visual appeal of the application.

Conclusion:

By following these steps, you’ll empower your Django application with a functional and visually-pleasing restaurant menu. Users can navigate through categorized meals, delve into details for each item, and appreciate the user-friendly interface facilitated by Bootstrap styling. This approach equips you with reusable skills applicable to many future Django projects you embark on.

Hi! I'm Sugashini Yogesh, an aspiring Technical Content Writer. *I'm passionate about making complex tech understandable.* Whether it's web apps, mobile development, or the world of DevOps, I love turning technical jargon into clear and concise instructions. *I'm a quick learner with a knack for picking up new technologies.* In my free time, I enjoy building small applications using the latest JavaScript libraries. My background in blogging has honed my writing and research skills. *Let's chat about the exciting world of tech!* I'm eager to learn and contribute to clear, user-friendly content.

Write A Comment