Skip to main content

Basic Website: Django

 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. (The HTML and CSS codes are rudimentary.)

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

Open the terminal and start by installing Django with the following command:

pip install django

Create a Django project (Let’s call it profile) with the following command:

django-admin startproject Profile

Once the project has been completely created, navigate to the project file:

cd Profile

Create an application (Let’s call it base) within the project (this comes in handy for large multi-aspect websites) :

django-admin startapp base

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

Add the following element to the end of the list: (This is necessary for the project to be base app to be linked to the Profile project)

'base.apps.BaseConfig',

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

Add the following element to the ‘DIRS’ list: (This is necessary to add HTML code)

BASE_DIR / 'templates',

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

Add the following list on the line after the STATIC_URL variable

STATICFILES_DIRS = [
BASE_DIR / 'static'
]

This is how you settings.py should look like:

Settings.py

"""
Django settings for Profile project.
Generated by 'django-admin startproject' using Django 4.0.2.For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
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
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# 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 definitionINSTALLED_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
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
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
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'static'
]
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

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

Import an additional function into the file:

from django.urls import include

Add an additional element to the urlpatterns list:

path('', include('base.urls')),

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

urls.py

"""Profile URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
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).

Paste the following code to the views.py file:

views.py

from django.shortcuts import renderdef 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

Add the following code to the base/urls.py file:

urls.py (in the base directory)

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

Add a style.css file in the styles directory and add the following code to the style.css file:

styles.css

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)

Create a file called navbar.html for the navigation bar and add the following code to it:

navbar.html

{% 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.

Create a file called home.html and add the following code to it:

home.html

{% 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.

Create a file called projects.html and add the following code to it:

projects.html

{% 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, 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>
</div>
<div id="project" class="project-item">
<h2>PROJECT 2 NAME </h2>
<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>
</div>
</div>
</center>
</section>

Create a file called contact.html and add the following code to it:

contact.html

{% 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 the terminal and run the following commands:

cd profile
python manage.py runserver

Click on the link in the output of the command (http://127.0.0.1:8000/) and your Django website will be live!!

Popular posts from this blog

Cloud Computing: Google Cloud

Cloud Computing is defined as the services offered through remote servers on the internet. These services might include database storage, applications, compute power and other IT resources over the pay-as-you-go pricing approach. The remote server allows users to save, modify, or process data on the internet or cloud-based platform instead of storing it on a local server or their devices. Cloud computing is evolving due to fast performance, better manageability, and less maintenance. It helps organizations to minimize the number of resources and overall infrastructure costs. Additionally, it helps IT teams better focus on the important applications, services, and processes and achieve the company's goals. Typically, the cloud-computing providers offer their services according to the following three standard models:  Platform as a Service (PaaS)  Software as a Service (SaaS)  Infrastructure as a Service (IaaS) Google Cloud Platform (GCP) is a suite of cloud computing servi...

Web Development: Backend

 Web development refers to the building, creating, and maintaining of websites. It includes aspects such as web design, web publishing, web programming, and database management. It is the creation of an application that works over the internet i.e. websites. Building a website comprises 2 fundamentals: Frontend Backend Backend refers to the the server side of a website. It is the part of the website that users cannot see and interact. It is the portion of software that does not come in direct contact with the users. It is used to store and arrange data. Backend Development can be done with the assistance of: PHP NodeJS Python  Ruby Java PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP uses composer as its package manager. Composer is an application-level package manager for the PHP programming language that provides a standard format for managing dependencies of PHP software and required libraries. Testing can be do...

Web Development: Frontend

Web development refers to the building, creating, and maintaining of websites. It includes aspects such as web design, web publishing, web programming, and database management. It is the creation of an application that works over the internet i.e. websites. Building a website comprises 2 fundamentals: Frontend Backend  Frontend Development refers to the 'Client Side' of the website, or in simpler terms, the visual part of any website.  The prerequisites of frontend development include: HTML CSS JS HTML stands for HyperText Markup Language. It is used to design the front end portion of web pages using markup language. It acts as a skeleton for a website since it is used to make the structure of a website. CSS (Cascading Style Sheets) is a simply designed language intended to simplify the process of making web pages presentable. It is used to style our website. CSS can further be classified into the following: CSS Library: Pure CSS CSS Frameworks: Bootstrap, Bulma, Foundation, M...