Django Web Application sample using MongoDB

  • This tutorial covers setting up a python Django web application using MongoDB database.
    Learn how to set up Django framework for first time in your machine, how to run the Django applications, basic set up for your first HTML page, database CRUD actions like create a record, fetch data, update a record and delete.
    In this sample, PyMongo adapter is used to connect to the MongoDB database.

  • Install Python and setup Virtual Environment

    Download and install the latest version of python from Python Website if not already done.

    Keep your favourite Python editor ready. This can be a basic notepad application available by default for your OS or you can download and install any free editor like VS Code.

    Next step is to set up a virtual environment.
    For that, go to the command prompt and cd to the folder where you are going to keep your project.
    Run command python -m venv CarSalesVENV to create a project folder CarSales and a virtual environment for it.
    Activate the VE using command:

    For Windows:
    CarSalesVENV\Scripts\activate.bat
    For Linux, macOS:
    source CarSalesVENV /bin/activate

    After VE activation, from cmd type cd CarSalesVENV to navigate to the project folder.

  • Install PyMongo

    For MongoDB connection we are going to use the PyMongo library. Install this using the command: pip install pymongo or pip3.9 install pymongo

  • Install Django Framework

    To install Django, run command pip install django or pip3.9 install django (if we are using Python 3.9).

    Run pip freeze or pip3.9 freeze to check if Django installed successfully. Should give an output like this.

    asgiref==3.5.2
    Django==4.0.4
    pymongo==4.1.1
    sqlparse==0.4.2
    tzdata==2022.1
    
  • Initial steps for Django Web Apps

    A Django application is structured as a top level Django Project with zero or more Django Apps (modules) within it. Project will contain common codes specific to all sub apps.
    For our example, we will create a project within our virtual environment and an app inside it. Let us go through the steps one by one.

    Step 1: Create Django Project

    To create a project run:
    django-admin startproject CarSalesProject .

    Running the above command will create a project named CarSalesProject and a python file manage.py will get added. We are providing a ' .' after the project name to avoid an additional folder with the same name being created. See the folder structure after creating project.

    Django and MongoDB - Config
    Step 2: Create Django App

    Now on, we don't have to use django-admin in our commands. Use the below command to create our CarSales app.
    python manage.py startapp CarSales

    A new app folder will get created with some files in it. For more details on the files created, you can refer Django Basics.
    New folder structure below:

    Django and MongoDB - Config
    Step 3: Include app to our project

    For this, in settings.py, add our new app CarSales (case sensitive) to INSTALLED_APPS list as below.

    Django and MongoDB - Settings
  • Loading First HTML Page

    This part explains how we are going to define the routes and where to place our html files. We are going to work on four files highlighted in below image. An html file and 2 urls.py file and views.py file
    Html files should be placed within a folder named templates. Create this folder in our CarSales app.

    Django and MongoDB - Config

    Add a new html file carslist.html, inside templates folder.
    We should have 2 urls.py, one inside, project folder and one inside app folder. If not available, create these files. urls.py in project folder adds a reference to the app urls.py.
    In app urls.py we define the urlpatterns for this module.
    In views.py we define the htmls to render for each route. Code provided below.

    Run the app using command python manage.py runserver
    Copy the url from cmd and browse. We should get below output window.

    Django and MongoDB - First Page
  • MongoDB Database Setup

    We will use the PyMongo adapter to create database and a table and insert data to it.
    Create a file named dbscripts.py in the same Virtual Environment folder and paste the below code in it.
    Run this file using command py dbscripts.py or python dbscripts.py

    This set of code connects to the local MongoDB client and then creates a database and a table in it. You should have MongoDB installed locally in your machine or use a valid server url in the below code.
    Then we are inserting five records to the table.

    Copied
    import pymongo
    
    carsalesClient = pymongo.MongoClient("mongodb://localhost:27017/")
    carsalesDB = carsalesClient["CarSales"]
    tblCars = carsalesDB["TblCars"]
    
    carslist = [
      { "ID": 1, "Name": "Toyota Camry", "Year": 2018, "Price": 2000 },
      { "ID": 2, "Name": "Honda Civic", "Year": 2019, "Price": 2200 },
      { "ID": 3, "Name": "Chevrolet Silverado", "Year": 2017, "Price": 1800 },
      { "ID": 4, "Name": "Ford F-150", "Year": 2020, "Price": 2500 },
      { "ID": 5, "Name": "Nissan Altima", "Year": 2021, "Price": 3000 }
    ]
    
    tbl = tblCars.insert_many(carslist)
    print(tbl.inserted_ids)
    
  • Fetch data from MongoDB DB and list

    carslist.html is going to hold the list of cars available for sale. To list the items, add below code in the body of html. Here, we using a for loop to bind the data to a table.
    Now modify views.py as below to read the data from MongoDB database. Import pymongo. Bind data to the html using render function.

    For styling we will use Bootstrap 5. Add below 2 lines inside head of html.

    
        <link rel="stylesheet" crossorigin="anonymous"
    	href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" >
        
    	<script crossorigin="anonymous"
    	src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" >
    	</script>
    
    

    On refreshing the web page, we will get the below output window.

    Django and MongoDB - List Items
  • Insert new item to MongoDB

    Add a new button in the carslist.html above the table.

        <a class="btn btn-primary" href="addcar">Add New Car</a>
    

    Add a new url pattern for addcar in the app urls.py.

    from django.urls import path
    from . import views
    urlpatterns = [
        path('', views.carslist, name = 'carslist'),
        path('addcar', views.addcar, name = 'addcar')
    ]
    

    Add new html file addcar.html in templates folder and place below code.
    Html uses forms. To handle forms in Django we need a form class. Add an new file forms.py in the CarSales app folder and include the form details.
    Then add below code in view.py as the second function below carslist function.

    Also import the form class and redirect in view.py

    from django.shortcuts import render, redirect
    from django.apps import apps
    import pymongo
    
    from .forms import CarForm
    

    In the view.py, we are defining a new function for addcar. We are using the same method for GET and POST. GET is just rendering addcar.html. In POST, we are reading data from form controls and save data to MongoDB table and then redirect to list page.

    In HTML page, we are defining a form with 4 text boxes. Each has a name provided. This name is used in the view.py while reading data from controls.
    In the HTML form, we have to add {% csrf_token %} next to form tag to avoid csrf verification failed error. On rerun, we can navigate to Create page as below and add new Car.

    Django and MongoDB - Add an Item
  • Update items - MongoDB

    For update and delete we will add 2 links in the carslist.html page as below.

    Copied
    <table class="table">
        <thead>
            <tr>
            <th scope="col">Id</th>
            <th scope="col">Name</th>
            <th scope="col">Year</th>
            <th scope="col">Price</th>
            <th scope="col">Edit</th>
            <th scope="col">Delete</th>
            </tr>
        </thead>
        <tbody>
            {% for car in cars %}
                <tr>
                    <td>{{ car.id }}</th>
                    <td>{{ car.name }}</td>
                    <td>{{ car.year }}</td>
                    <td>{{ car.price }}</td>
                    <td><a href='updatecar/{{ car.id }}'>Edit</a></td>
                    <td><a href='deletecar/{{ car.id }}'>Delete</a></td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    

    For easier understanding, we are going to keep separate routes for create and update. For update, we will provide the route name updatecar.

    In addcar.html, in order to populate the values, we have to use the value attribute and bind the car object values as in html provided below.

    In views.py, add new updatecar function. In GET, we are filtering details based on selected ID and assigning it to a list variable and pass it to the addcar.html page. In POST, we are calling the update_one method to update records based on the selected ID.

    Note: Disable the ID textbox to not make changes to ID. Here we are not doing it and if ID is changed no update will happen.

    Also, add a new url pattern for updatecar in the app urls.py.

    from django.urls import path
    from . import views
    urlpatterns = [
        path('', views.carslist, name = 'carslist'),
        path('addcar', views.addcar, name = 'addcar'),
        path('updatecar/<int:id>', views.updatecar, name = 'updatecar')
    ]
    

    After the above changes, update will work, but create will throw an error. To fix this, change the render line of addcar as below.

    return render(request, 'addcar.html', {'car':{}})
    

    We are binding an empty car object to make it working.

  • Delete an Item from MongoDB

    For delete, add a new route deletecar and call delete_one method as below.

    Copied
    def deletecar(request, id):
        carsalesDB = connectDB()
        tblCars = carsalesDB["TblCars"]
        tblCars.delete_one({ "ID": id })
        return redirect('carslist')
    

    Then add new url pattern for deletecar in the app urls.py.

    from django.urls import path
    from . import views
    urlpatterns = [
        path('', views.carslist, name = 'carslist'),
        path('addcar', views.addcar, name = 'addcar'),
        path('updatecar/<int:id>', views.updatecar, name = 'updatecar'),
        path('deletecar/<int:id>', views.deletecar, name = 'deletecar')
    ]
    
  • Django CRUD with MongoDB database - Complete code

    Below listed are the files with code changes. Also a one line change required in Settings.py which is explained at the beginning.

Absolute Code Works - Python Topics