DEV Community

Cover image for Django Tutorial #5: Create the Home Page
Eric Hu
Eric Hu

Posted on • Originally published at techjblog.com

Django Tutorial #5: Create the Home Page

You can download the source code of this tutorial here.
https://www.techjblog.com/index.php/django-tutorial-for-beginners/

Now, it is time for us to dive into our project. To get familiar with everything, we start by creating only the home page.

Since this is the first time that we work with all the components we talked about, the model, admin, view, URL configuration, and template, I’ll try to keep things simple.

Create the First Model

First, we create a model named General which will store the general information about our website.

from django.db import models


# Create your models here.
class General(models.Model):
    name = models.CharField(max_length=100)
    logo = models.ImageField(upload_to='logo')
    description = models.TextField()

    def __str__(self):
        return self.name
Enter fullscreen mode Exit fullscreen mode

Let’s take a closer look at this model.

Line 6, this column stores the name of our website, and the maximum length is set to be 100.

The CharField is called a field type, it determines what kind of information is stored in the database as well as what kind of field will be shown on the admin page. For example, a CharField means a string will be stored in the database and a text field will be shown:

img

Here is a list of all the field types that you can use: https://docs.djangoproject.com/en/3.1/ref/models/fields/#field-types

Line 7, the ImageField means an image upload button will be shown in the admin panel:

img

And contrary to what you might believe, this logo column in the database doesn’t actually store the image that was uploaded. Instead, it stores an URL, a path that points to the image. In this case, all the logo images will be uploaded to the /logo directory, which is specified by the upload_to option.

The upload_to and max_length are just two examples of a field option. Field options provide extra information for the field. For instance, default gives the default value for the field, and null determines whether the field can be empty or not.

Here is a list of all the field options that you can use: https://docs.djangoproject.com/en/3.1/ref/models/fields/#field-options

Line 8, this column stores the description for our website. Again, a string will be stored in the database, except, a bigger text box will be shown in the admin.

And that’s it, it is a lot easier compared to Laravel since we do not need to edit the migration files. All that’s left to do is run the following commands in the terminal. The first one generates the migration files and the second one applies the migration.

python manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Setup Django Admin

The admin panel setup is rather simple since we don’t need and fancy functions for now.

from django.contrib import admin
from .models import General


# Register your models here.
admin.site.register(General)
Enter fullscreen mode Exit fullscreen mode

Now, open the development server, and then the admin panel. Fill out the name, description and upload the logo.

img

Create the Home View

Next, it is time to create our home view:

from django.shortcuts import render
from .models import General


# Create your views here.
def home(request):
    general = General.objects.first()

    return render(request, 'home.html', {
        'general': general,
    })
Enter fullscreen mode Exit fullscreen mode

Line 2, we need to first import the General model we just created.

Line 7, this line of code will fetch the first entry of the General, and assign it to the variable general.

Line 9 to 11, finally, we send the general variable to the home template to be rendered. We will create the template in the following steps.

URL Configuration

However, before we can create the template, we need to make sure the URL configuration is correct, so that we can see the result in the browser.

Django_31_Tutorial/urls.py
from django.urls import path, include

urlpatterns = [
    path('', include('blog.urls'))
]
blog/urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
    path('', views.home)
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Enter fullscreen mode Exit fullscreen mode

There is a slight difference in the last line. That is because we uploaded an image file, by adding this line of code, we will able to access it in the template.

However, remember this is for the development environment, it is not suitable for production. We’ll talk about deploying static and media files in the final part of this tutorial.

Create the Home Template

The final step would be to create the home template. To make the page look better, we’ll use the bootstrap framework. Assuming you already understand how HTML and CSS work.

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>{{ general.name }}</title>

    <!-- Bootstrap core CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
          integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

</head>

<style>
    body {
        padding-top: 56px;
    }

</style>

<body>

<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
    <div class="container">
        <a class="navbar-brand" href="#">
            <img src="{{ general.logo.url }}" width="60" height="40" class="d-inline-block align-top" alt="" loading="lazy">
            {{ general.name }}</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive"
                aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarResponsive">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Home
                        <span class="sr-only">(current)</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">About</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

<!-- Page Content -->
<div class="container">

    <div class="row">

        <!-- Blog Entries Column -->
        <div class="col-md-8">

            <h1 class="my-4">{{ general.name }}
                <small>Home Page</small>
            </h1>

            <p>{{ general.description }}</p>
        </div>

        <!-- Sidebar Widgets Column -->
        <div class="col-md-4">

            <!-- Search Widget -->
            <div class="card my-4">
                <h5 class="card-header">Search</h5>
                <div class="card-body">
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="Search for...">
                        <span class="input-group-append">
                <button class="btn btn-secondary" type="button">Go!</button>
              </span>
                    </div>
                </div>
            </div>

            <!-- Categories Widget -->
            <div class="card my-4">
                <h5 class="card-header">Categories</h5>
                <div class="card-body">
                    <div class="row">
                        <div class="col-lg-6">
                            <ul class="list-unstyled mb-0">
                                <li>
                                    <a href="#">Web Design</a>
                                </li>
                                <li>
                                    <a href="#">HTML</a>
                                </li>
                                <li>
                                    <a href="#">Freebies</a>
                                </li>
                            </ul>
                        </div>
                        <div class="col-lg-6">
                            <ul class="list-unstyled mb-0">
                                <li>
                                    <a href="#">JavaScript</a>
                                </li>
                                <li>
                                    <a href="#">CSS</a>
                                </li>
                                <li>
                                    <a href="#">Tutorials</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Side Widget -->
            <div class="card my-4">
                <h5 class="card-header">Side Widget</h5>
                <div class="card-body">
                    You can put anything you want inside of these side widgets. They are easy to use, and feature the
                    new Bootstrap 4 card containers!
                </div>
            </div>

        </div>

    </div>
    <!-- /.row -->

</div>
<!-- /.container -->

<!-- Footer -->
<footer class="py-5 bg-dark">
    <div class="container">
        <p class="m-0 text-center text-white">Copyright &copy; Your Website 2020</p>
    </div>
    <!-- /.container -->
</footer>

<!-- Bootstrap core JavaScript -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
        crossorigin="anonymous"></script>

</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Line 11, remember we sent a general variable to the template? That variable has three components, and this is how we can access the name component.

Line 32, {{ general.logo.url }} is how we can access the URL that points to the image we uploaded.

Finally, open the browser and go to http://127.0.0.1:8000/.

img

Discussion (0)