Web Development with Django 2.0

PAWAN THAKUR
HimachaliProgrammer
5 min readDec 27, 2017
Django best python framework for web development

Django is a robust, open-source, Python-based framework for building web applications. it is already mature and widely-used with a large community behind it.

Being a Django developer, I will share my knowledge of using Django in a professional way by keeping the python philosophy in mind

“Simple is better then complex”

“complex is better then complicated”.

I assume that you are well aware of python programming language, html, css, java script and jQuery. Knowledge is of bootstrap is a plus. I also assume that you are well aware of linux based OS systems and bash scripting.

  1. Django — Writing the first app

Installation

  • Install latest version of python using official link. Current version is 3.6.4. Then install more modules using following code snippet:
# install virtualenv using pip3
$ pip3 install virtualenv # pip3 is installed along with python3
# create prog and .virtualenv directory in home folder
$ mkdir ~/prog
$ mkdir ~/.virtualenv
#Create virtual environment for your_project
$ virtualenv ~/.virtualenv/django_for_real_developers
# activate virtual environment
$ source ~/.virtualenv/django_for_real_developers/bin/activate
# install Django version 2.0
$ pip install django==2.0

Write the first django program

$ cd ~/prog  #change current directory to development folder
$ django-admin startproject main #create basic template for project
#rename outer main folder to project_name
$ mv main DjangoForRealDevelopers
$ cd DjangoForRealDevelopers
$ ./manage.py migrate # initial DB migration
$ ./manage.py runserver # run development server at localhost:8000
current files structure in DjangoForRealDevelopers
Development Server output

Create Django App

$ ./manage.py startapp hello
folder structure after startapp

Now, create index.html and urls.py in hello

$ mkdir hello/templates/hello
$ touch hello/templates/hello/index.html
$ touch hello/urls.py

hello/templates/hello/index.html

<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
<title>{% block title %} {{title}} {% endblock %} -DjangoForRealDevelopers</title>
</head>
<body>
<h1> Hello World ! </h1>
</body>
</html><body>
<h1> Hello World ! </h1>
</body>
</html>

hello/urls.py

from django.urls import include, path
from . import views
app_name = 'hello' # required since Django 2.0
urlpatterns = [
path('', views.index, name="home"),
]

Change content of hello/views.py

from django.shortcuts import render# Create your views here.
def index(request):
context ={
'title' : "Home Page",
}
return render(request, "hello/index.html", context)

Now modify main/settings.py and main/urls.py

main/settings.py

INSTALLED_APPS = [
'hello.apps.HelloConfig', #Added for hello app
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

main/urls.py

from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('hello.urls', namespace='hello')),
]

Now files structure will look like

Run the development server to view this result

hello world output

2. Django — directly access html file from templates without creating view in views.py

To access html file directly for certain url path we need to use generic class based view. It is very helpful for developers while testing and learning new things that do not required view based controller.

/hello/urls.py for direct access to html

from django.urls import path
from django.views.generic import TemplateView
urlpatterns = [
path('', TemplateView.as_view(template_name='hello/index.html'), name="home"),

]

3. Django — Using professional template structure and bootstrap

Using files structure as shown in this tutorial allows apps re-usability — read More. It also helps to avoid duplicate code snippets.

Bootstrap on other hand helps us to modify html look and feel in beautiful way without writing much code.

Create templates folder in home directory and put base.html and header.html in it. Then modify main/settings.py to accept this change:

main/settings.py

...
EMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'], # edit this line
'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',
],
},
},
]
...

templates/base.html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- The above 3 meta tags *must* come first in the head -->
<title>{% block title %} {{title}} {% endblock %} -DjangoForRealDevelopers</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
{% block css %}
<!-- load custom css -->
{% endblock %}
</head>
<body>
{% block header %}{% include "header.html" %}{% endblock %}
{% block content %}<h1> Hello World! </h1>{% endblock content %}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
{% block script %}
<!-- load custom js -->
{% endblock %}
</body>
</html>

templates/header.html

{% load staticfiles %}
<div class="container-fluid">
<nav class="navbar navbar-expand-md navbar-light bg-secondary mx-0" style="z-index:2;">
<a class="navbar-brand" href="{% url 'hello:home' %}">
Django For Real Developers
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<div class="navbar-nav ml-auto py-1" >
<a id="home" class="nav-item nav-link active" href="/#home"> HOME </a>
</div>
</div>
</nav>
</div>

Now modify hello/templates/hello/index.html

{% extends 'base.html' %}
{% load staticfiles %}
{% block title %} Welcome {% endblock %}
{% block css %}
{{block.super}}
<link href="{% static 'hello/index.css' %}" rel="stylesheet" />
{% endblock %}
{% block script %}
{{block.super}}
<script src="{% static 'hello/index.js'%}"></script>
{% endblock %}
{% block content %}
<div class="container bg-light p-5">
<div class="row">
<div class="col-auto mx-auto">
Welcome to django with bootstrap !<br />
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
{% if perms.hello %}
have permission
{% else %}
no permission
{% endif %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
</div>
</div>
</div>
{% endblock %}

Now create hello/static/hello/index.css and hello/static/hello/index.js

hello/static/hello/index.js

<script>
$(function(){
// you jQuery code
});
</script>

hello/static/hello/index.css

.container{
margin-top: 1rem;
}

Now run the development server to see update result

$ ./manage.py runserver

That’s all for now. I hope it will help to someone.

This is my first post. I would love to hear some feedback from others, about this setup, how could I potentially improve it, anything that needs changing or could be done better, etc.

--

--