Create a Simple Django Boilerplate (Part 3)

Create a Simple Django Boilerplate (Part 3)

In this tutorial, we will write views that reads records from the database and render results to the template.

Introduction

This was what we achieved in part 2 of the tutorial.

  1. Activated our application
  2. Set up URL Configurations for our project
  3. Created a basic view template

Create a model

We need to first create models to store data. In Django, each model maps to a single database table.

We can make use of Django's built-in database-abstraction API to create, read, update and delete (CRUD) objects after we have created our data models.

Add the following code to boilerplate/models.py.

from django.db import models

class Demo(models.Model):
    demo_title = models.CharField(max_length=200)
    demo_description = models.CharField(max_length=200)

    def __str__(self):
        return self.demo_title

We created a Demo model that subclasses django.db.models.Model.

Within the model, we have created two fields, demo_title and demo_description. The fields are represented by an instance of a CharField class for character fields.

The database will use the name of each field as the column name. Some fields have optional arguments. The Charfield class have a required argument of max_length or the maximum number of characters for this field.

In this example, we set a maximum character limit of 200 for each field. You can read about model fields from Django's documentation regarding the different arguments and field types.

Let's store the changes that we have made to the model by running the following command.

$ python manage.py makemigrations boilerplate

You should see the following in your terminal.

Migrations for 'boilerplate':
    boilerplate/migrations/0001_initial.py
    - Create model Demo

Run the migrate command to create the model tables in our database.

$ python manage.py migrate

We need to create login credentials to access the admin page. Enter the following command to create one.

$ python manage.py createsuperuser

Start the development server and visit http://localhost:8000/admin to access the Django admin page. Log in using your new credentials.

Django Admin

The admin page looks pretty bare.

Let's edit the admin view to display our demo_title and demo_description fields.

Add the following code to boilerplate/admin.py.

from django.contrib import admin

from .models import Demo
admin.site.register(Demo)

Refresh the admin page and you will see a new BOILERPLATE fieldset.

Click the Add button next to Demos to add a new title and description.

After you click SAVE, Django will notify you that the new object was added.

Display the object

Paste the following into boilerplate/views.py.

from django.shortcuts import render

from .models import Demo

def index(request):
    latest_demo_list = Demo.objects.all()
    context = {'latest_demo_list': latest_demo_list}
    return render(request, 'boilerplate/index.html', context)

A couple of things are happening here.

  1. Imported our Demo model from models.py.
  2. Defined an index view and construct a queryset to obtain the Demo objects.
  3. Stored the queryset as a key/value mapping context and pass it to our template.
  4. Filled a context and return an HttpResponse object with the results of the rendered template using the Django render() shortcut.

Edit boilerplate/templates/boilerplate/index.html.

<div>
    {% for demo in latest_demo_list %}
    <h1>{{ demo.demo_title }}</h1>
    <p>{{ demo.demo_description }}</p>
    {% endfor %}
</div>

We looped over each item in the latestdemolist array and display the list of demo objects using the for tag.

Django evaluates the variables {{ demo.demo_title }} and {{ demo.demo_description }}; replaces them with the appropriate attribute of the demo object and renders the results.

In this case, {{ demo.demo_title }} is replaced with "This is a test title." and {{ demo.demo_description }} is replaced with "This is a test description.".

Visit http://localhost:8000/ to see the changes.

In part 4 of the tutorial, we will look at integrating Bootstrap with Django.

Latest Posts

Top ten things I Google at workTop ten things I Google at work
How to order pizza the RPA way!How to order pizza the RPA way!
How Gordon Ramsay saved our struggling development teamHow Gordon Ramsay saved our struggling development team