Python and Django: Building a Restaurant Review Website

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating a Django Project
  5. Creating the Restaurant Model
  6. Creating the Review Model
  7. Setting Up the Database
  8. Creating the Views
  9. Creating the Templates
  10. Creating the URL Patterns
  11. Running the Django Development Server
  12. Conclusion

Introduction

In this tutorial, we will build a restaurant review website using Python and Django. By the end of this tutorial, you will have a fully functional website where users can browse and review restaurants.

Prerequisites

Before starting this tutorial, you should have a basic understanding of Python programming language. Familiarity with Django framework will be beneficial, but not mandatory.

Setup

To get started, make sure you have Python and Django installed on your machine. You can install Python from the official Python website (https://www.python.org) and Django using pip, the Python package installer, by running the following command in your terminal: shell pip install django

Creating a Django Project

Let’s start by creating a new Django project. Open your terminal and navigate to the directory where you want to create the project. Then, run the following command: shell django-admin startproject restaurant_review This will create a new directory named restaurant_review containing all the necessary files for your Django project.

Creating the Restaurant Model

Now, let’s create a model to represent the restaurants in our website. Inside the restaurant_review directory, navigate to the restaurant_review directory (the one containing settings.py), and open the models.py file. Replace the contents of the file with the following code: ```python from django.db import models

class Restaurant(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    address = models.CharField(max_length=200)

    def __str__(self):
        return self.name
``` This code defines a `Restaurant` model with three fields: `name`, `description`, and `address`. The `__str__` method is used to display the name of the restaurant in a human-readable format.

Creating the Review Model

Next, let’s create a model to represent the reviews for each restaurant. In the same models.py file, add the following code: ```python from django.contrib.auth.models import User

class Review(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    rating = models.IntegerField()
    comment = models.TextField()

    def __str__(self):
        return f"Review by {self.user.username} for {self.restaurant.name}"
``` This code defines a `Review` model with four fields: `restaurant`, `user`, `rating`, and `comment`. The `restaurant` field is a foreign key to the `Restaurant` model, and the `user` field is a foreign key to the built-in `User` model provided by Django.

Setting Up the Database

Before we can use the models we created, we need to set up the database. Open the settings.py file inside the restaurant_review directory, and locate the DATABASES section. Update it with your database credentials or use the default SQLite database as shown below: python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }

Creating the Views

Now, let’s create the views for our website. Inside the restaurant_review directory, create a new directory named restaurants. Inside the restaurants directory, create a new file named views.py and add the following code: ```python from django.shortcuts import render from .models import Restaurant

def restaurant_list(request):
    restaurants = Restaurant.objects.all()
    return render(request, 'restaurants/restaurant_list.html', {'restaurants': restaurants})

def restaurant_detail(request, pk):
    restaurant = Restaurant.objects.get(pk=pk)
    return render(request, 'restaurants/restaurant_detail.html', {'restaurant': restaurant})
``` This code defines two views: `restaurant_list` and `restaurant_detail`. The `restaurant_list` view retrieves all the restaurants from the database and renders them using the `restaurant_list.html` template. The `restaurant_detail` view retrieves a specific restaurant based on its primary key (`pk`) and renders it using the `restaurant_detail.html` template.

Creating the Templates

Let’s create the HTML templates for our views. Inside the restaurants directory, create a new directory named templates. Inside the templates directory, create another directory named restaurants. Inside the restaurants directory, create two HTML files: restaurant_list.html and restaurant_detail.html. In each file, add the following code:

restaurant_list.html: ```html

{% for restaurant in restaurants %}
    <h2>{{ restaurant.name }}</h2>
    <p>{{ restaurant.description }}</p>
    <p>{{ restaurant.address }}</p>
    <a href="{% url 'restaurant_detail' restaurant.pk %}">View Details</a>
{% endfor %}

``` restaurant_detail.html:
```html

<h2>{{ restaurant.name }}</h2>
<p>{{ restaurant.description }}</p>
<p>{{ restaurant.address }}</p>

``` These templates use Django template language to display the restaurant information. They also include a link to view the details of each restaurant.

Creating the URL Patterns

Now, let’s create the URL patterns for our views. Inside the restaurants directory, create a new file named urls.py and add the following code: ```python from django.urls import path from . import views

urlpatterns = [
    path('', views.restaurant_list, name='restaurant_list'),
    path('<int:pk>/', views.restaurant_detail, name='restaurant_detail'),
]
``` This code defines the two URL patterns for our views. The first pattern matches the root URL and maps it to the `restaurant_list` view. The second pattern matches a URL with an integer parameter (`<int:pk>/`) and maps it to the `restaurant_detail` view.

Running the Django Development Server

We are now ready to run our Django development server and see our website in action. Open your terminal, navigate to the restaurant_review directory (the one containing manage.py), and run the following command: shell python manage.py runserver This will start the development server. Open your web browser and visit http://localhost:8000 to see the list of restaurants. Clicking on a restaurant will take you to its details page.

Congratulations! You have successfully built a restaurant review website using Python and Django.

Conclusion

In this tutorial, we learned how to create a Django project, define models for restaurants and reviews, set up the database, create views and templates, and handle URL routing. We covered the basics of building a website using Django and you can now expand on this project by adding more features such as user authentication, search functionality, and user reviews.

Remember to explore Django’s extensive documentation and community resources to further enhance your Django development skills.