Open In App

Django – Creating a Multi-Page Website

Django is a python based open-source framework used for web development. Django allows the usage of the M-T-V (Model-Templates-View) architectural pattern for the creation and deployment of a functional website. 

This article aims at creating a multipage personal profile website using Django to explain all the main concepts and aspects of the Django framework. 



Note: The HTML and CSS codes in the article below are rudimentary.

Implementation:

Start off by creating a new project in any IDE that supports Python.



pip install django
django-admin startproject Profile
cd Profile
django-admin startapp base

Navigate to the settings.py file in the profile/profile directory and look for a list name INSTALLED_APPS 

'base.apps.BaseConfig',

Scroll down to a list named TEMPLATED in the settings.py file

BASE_DIR / 'templates',

Scroll down further and you will find a variable called STATIC_URL.

STATICFILES_DIRS = [
    BASE_DIR / 'static'
]

This is what your settings.py should look like:




"""
Django settings for Profile project.
  
Generated by 'django-admin startproject' using Django 4.0.2.
  
For more information on this file, see
  
For the full list of settings and their values, see
"""
  
from pathlib import Path
  
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
  
  
# Quick-start development settings - unsuitable for production
  
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-%y9#-d_f74fdq6t6qal(51b4-j1v7f)g+c&7cb1g_wuz_94xq%'
  
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
  
ALLOWED_HOSTS = []
  
  
# Application definition
  
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'base.apps.BaseConfig',
]
  
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
  
ROOT_URLCONF = 'Profile.urls'
  
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR / 'templates',
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
  
WSGI_APPLICATION = 'Profile.wsgi.application'
  
  
# Database
  
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
  
  
# Password validation
  
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
  
  
# Internationalization
  
LANGUAGE_CODE = 'en-us'
  
TIME_ZONE = 'UTC'
  
USE_I18N = True
  
USE_TZ = True
  
  
# Static files (CSS, JavaScript, Images)
  
STATIC_URL = 'static/'
STATICFILES_DIRS = [
    BASE_DIR / 'static'
]
  
# Default primary key field type
  
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Now, navigate to the urls.py file in the Profile/Profile directory.

from django.urls import include
path('', include('base.urls')),

This is what your urls.py file should look like:




"""Profile URL Configuration
  
The `urlpatterns` list routes URLs to views. For more information please see:
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('base.urls')),
]

Now, navigate to the views.py file in the Profile/base directory:

Here we create the varied pages and assign the respective HTML files (which we’ll create later).




from django.shortcuts import render
  
def home(request):
    return render(request, "home.html")
  
def projects(request):
    return render(request, "projects.html")
  
def contact(request):
    return render(request, "contact.html")

Create a new file called urls.py INSIDE THE Profile\base DIRECTORY

This file creates URLs to the respective web addresses mentioned in the views.py file




from django.urls import path
from . import views
  
urlpatterns = [
    path("", views.home, name="home"),
    path("projects/", views.projects, name="projects"),
    path("contact/", views.contact, name="contact"),
]

Now, for the static file (the file that contains .css files and images).

Create a new directory in the main Profile project file called static. The static file should be at the same hierarchical level as the manage.py file.

Inside this file create 2 more directories called styles and Images




    navbar {
      width: 100%;
      margin:0px 0;
    }
        navbar ul{
      width: 100%;
      list-style: none;
      margin: 0;
      padding: 0;
      overflow: hidden;
    }
  
    navbar ul li{
      width: 33%;
      float: left;
    }
        navbar ul li a{
      text-decoration: none;
      color: rgb(0, 0, 0);
      text-align: center;
      padding: 20px 0;
      display: block;
      width: 100%;
      background-color: rgb(160, 236, 145);
    }
  
    navbar ul li a:hover {
      background-color: rgb(11, 221, 29);
    }
  
  .home{
    margin-right: 5%;
    margin-top: 15px;
    margin-left: 15px;
    margin-bottom: 15px;
    padding-top: 15px;
    padding-left: 15px;
    padding-right: 5px;
    padding-bottom: 15px;
    border-radius: 10px;
    box-shadow: 15px 15px 15px black;
    text-align: justify;
    color: white;
    background-image: linear-gradient(rgb(129, 196, 235), rgb(5, 44, 151));
  }
  
  .project-area {
  
    background-repeat: no-repeat;
    background-position: left;
    box-sizing: border-box;
  }
  
  .project-item {
    width: 75%;
    margin-top:5px;
    margin-bottom:15px;
    margin-left: 5%;
    margin-right: 5%;
    padding-top:5px;
    padding-bottom:5px;
    padding-left: 30px;
    padding-right: 30px;
    border-radius: 10px;
    box-shadow: 10px 10px 40px gray;
    text-align: justify;
    color: white;
    background-color: black;
  }
  
  #project {
    border-left: 15px solid;
    border-image: linear-gradient(purple, tomato);
    border-image-slice: 1;
  }
  
  
#contact .contact-item {
  background-color: aquamarine;
  float: left;
    width: 20%;
    padding: 20px;
    text-align: center;
    border-radius: 10px;
    padding: 30px;
    margin: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    box-shadow: 15px 15px 15px black;
}

Add an image of yourself to the Images directory and rename it to ‘Profile_img’.

For the HTML files, create a new directory in the main Profile project file called templates. The templates file should be at the same hierarchical level as the manage.py file.




{% load static %}
<link rel="stylesheet" href="{% static 'styles/style.css' %}">
<navbar>
    <ul>
      <li><a href="/">Home</a></li>
      <li><a href="/projects">Projects</a></li>
      <li><a href="/contact">Contact</a></li>
    </ul>
</navbar>
<hr>

The first two lines in the above code are necessary to load the CSS code from the static directory, and to link the code in the CSS file to the HTML file.




{% include 'navbar.html' %}
{% load static %}
<link rel="stylesheet" href="{% static 'styles/style.css' %}">
<title>Home</title>
<section class="home">
        <center>
            <font size="6">
                  
<p>ABOUT ME </p>
  
            </font>
            <img src="{% static 'images/Profile_img.png' %}" width="200" height="200">
            <font size="4">
                  
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
  
            </font>
        </center>
</section>

The first line in the above code is used to directly add the navigation bar to the current page.




{% include 'navbar.html' %}
{% load static %}
<link rel="stylesheet" href="{% static 'styles/style.css' %}">
<title>Projects</title>
        <section class="project-area">
            <center>
            <font size="6">
                  
<p>PROJECTS</p>
  
            </font>
                <div id="project" class="project-item">
                    <h2>PROJECT 1 NAME</h2>
                      
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
                        Vestibulum dignissim, sapien et efficitur vulputate,
                         felis blandit metus, vitae eleifend nisl justo sed nunc.
                         Sed ut nunc malesuada, scelerisque mauris sed, hendrerit neque.
                         Morbi eget nisl non tellus posuere iaculis.
                         Nunc ut tincidunt est, a tempus tortor. Mauris lobortis felis elit,
                         quis euismod urna lacinia vitae. Morbi interdum diam in faucibus finibus.
                         Sed pellentesque sem a diam rhoncus, eu semper neque efficitur. </p>
  
                </div>
                <div id="project" class="project-item">
                    <h2>PROJECT 2 NAME </h2>
                      
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
                        Vestibulum dignissim, sapien et efficitur vulputate,
                         felis blandit metus, vitae eleifend nisl justo sed nunc.
                         Sed ut nunc malesuada, scelerisque mauris sed, hendrerit neque.
                         Morbi eget nisl non tellus posuere iaculis.
                         Nunc ut tincidunt est, a tempus tortor. Mauris lobortis felis elit,
                         quis euismod urna lacinia vitae. Morbi interdum diam in faucibus finibus.
                         Sed pellentesque sem a diam rhoncus, eu semper neque efficitur. </p>
  
                </div>
            </div>
            </center>
        </section>




{% include 'navbar.html' %}
{% load static %}
<link rel="stylesheet" href="{% static 'styles/style.css' %}">
<title>Contact</title>
  <section id="contact">
    <center>
      <font size="6">
            
<p>CONTACT INFO</p>
  
      </font>
        <div class="contact-item">
            <h1>Phone Number</h1>
            <h2>+xx-xxxxxxxxxx</h2>
          </div>
        </div>
        <div class="contact-item">
            <h1>Email</h1>
            <h2>xyz@example.com</h2>
          </div>
        </div>
        <div class="contact-item">
            <h1>Address</h1>
            <h2>City, State, Country</h2>
          </div>
        </div>
      </div>
    </div>
    </center>
  </section>

Now, for the final step, open up a new terminal and run the following commands:

cd profile
python manage.py runserver

Output:


Article Tags :