1: Introduction to Django


What is Django?

Released in 2005, Django is an open-source web framework written in the Python programming language.  Open-source allows users to freely modify and distribute a project's source code without fear of copyright infringement.  A web framework is collection of files that help users deploy web applications.  

 

How is Django used?

Django handles the complexity of web development by providing a clean design scheme so developers can focus more on the content of their web app and less on how to organize their code.  It's also extremely scalable with companies such as Instagram and YouTube using Django to deliver content to users in a fast and reliable manner. 

 

How does Django work?

Think of Django as a toolkit that comes with ready-to-implement features. A content administrative interface and other user authentication systems allow anyone interested in web development to quickly create web applications within a manner of hours. Following Django's Model-Template-View architectural pattern, you will edit Python files that connect to one another in order display different HTML templates.

If this seems a little overwhelming, don't worry this course is designed as a step-by-step tutorial that pairs application with elaboration. 

 








2: Creating a new virtual environment for Django


Now that you have a designated folder for virtual environments named code and understand the basics of the CLI and Python, it's time to start on your Django project. Just like using JupyterLab, we will create a new virtual environment for Django and install the package within it.

 

Access the code folder

macOS Terminal

User-Macbook:~ user$ cd desktop

User-Macbook:desktop user$ cd code

User-Macbook:code user$

Windows Command Prompt

C:\Users\Owner>cd desktop

C:\Users\Owner\desktop>cd code

C:\Users\Owner\desktop\code>

If you are using a new CLI window, type cd desktop in the prompt then cd code to enter into the recently created code folder or type cd desktop/code to execute both of the previous commands as one. 

If you are coming directly from the previous lesson Python Exercises, you should already be in the code directory.  If not, deactivate the jup envirnoment and cd .. back to the code folder.

 

Create a new virtual environment for your Django web app

macOS Terminal

User-Macbook:code user$ python3 -m venv env

Windows Command Prompt

C:\Users\Owner\desktop\code>py -m venv env

Inside the code directory, we will run the following command to create a new folder/virtual environment named env just like we did to create the jup virtual environment.

 

Activate the virtual environment folder from the CLI

macOS Terminal

User-Macbook:code user$ cd env

User-Macbook:env user$ source bin/activate

(env)User-Macbook:env user$

Windows Command Prompt

C:\Users\Owner\desktop\code>cd env

C:\Users\Owner\desktop\code\env>Scripts\activate

(env)C:\Users\Owner\desktop\code\env>

Next, let's activate the env virtual environment. We need to activate the environment to properly install Django and its dependencies only in this virtual environment and not on the entire local computer.

 

(For Future Use) Deactivate the virtual environment

macOS Terminal

(env)User-Macbook:env user$ deactivate

User-Macbook:env user$

Windows Command Prompt

(env)C:\Users\Owner\desktop\code\env>deactivate

C:\Users\Owner\desktop\code\env>

Remember, whenever you would like to move between virtual environments, deactivate the current virtual environment first. Do not deactivate the virtual environment if you are continuing directly to the next step.








3: Installing Django


Currently, you should be inside your activated env virtual environment:

macOS Terminal

(env)User-Macbook:env user$

Windows Command Prompt

(env) C:\Users\Owner\desktop\code\env>

 

Install Django from the CLI

macOS Terminal

(env)User-Macbook:env user$ pip install django==2.1.15
...

Windows Command Prompt

(env) C:\Users\Owner\desktop\code\env>pip install django==2.1.15
...

Run the command pip install django==2.1.15 to install django version 2.1.15 so we can eventually deploy using Amazon Web Services Elastic Beanstalk (AWS EB).  If you wish to install the latest version of Django, simply run the command pip install django but you will not be able to deploy using AWS EB given that versions after Django 2.2 are incompatible with this service.

Django may take a few minutes to install.  The prompt will reappear when the download and installation are complete.

 

Check the Django version from the CLI

macOS Terminal

(env)User-Macbook:env user$ pip show django
Name: Django
Version: 2.1.15
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
...

Windows Command Prompt

(env) C:\Users\Owner\desktop\code\env>pip show django
Name: Django
Version: 2.1.15
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
...

Run the command pip show django to see the version of Django installed in the virtual environment. Package details such as name, version, and summary will display in the CLI.

 

Create the Django project from the CLI

macOS Terminal

(env)User-Macbook:env user$ django-admin startproject mysite

Windows Command Prompt

(env) C:\Users\Owner\desktop\code\env>django-admin startproject mysite

Now that Django is installed, let's create the actual Django project folder to hold all of the web app code. django-admin is the command-line utility for administrative tasks. startproject is the function inside the django-admin file that actually creates the project and mysite is the arbitrary name we gave to the project. Together, this line of code creates a new Django folder named mysite with some basic Django project folders within it.

 

View the new Django project folder

macOS Terminal

(env)User-Macbook:env user$ ls
bin  include  lib  mysite  pyvenv.cfg

Windows Command Prompt

(env) C:\Users\Owner\desktop\code\env>dir

02/26/2019  09:17 AM    <DIR>          .
02/26/2019  09:17 AM    <DIR>          ..
02/26/2019  09:07 AM    <DIR>          Include
02/26/2019  09:07 AM    <DIR>          Lib
02/26/2019  09:17 AM    <DIR>          mysite
02/26/2019  09:07 AM               117 pyvenv.cfg
02/26/2019  09:10 AM    <DIR>          Scripts
               1 File(s)            117 bytes
               6 Dir(s)  858,690,949,120 bytes free

To view the newly created Django project folder in the env folder directory, run one of the CLI listing commands above. You should see the mysite folder listed along with several files automatically created by the Django installation.

 

Create the Django app from the CLI

macOS Terminal

(env)User-Macbook:env user$ cd mysite

(env)User-Macbook:mysite user$ python3 manage.py startapp main 

Windows Command Prompt

(env) C:\Users\Owner\desktop\code\env>cd mysite

(env) C:\Users\Owner\desktop\code\env\mysite>py manage.py startapp main

Although we have created our Django project and we're currently inside the env directory, we still need to create a Django app inside the mysite folder. A Django app is not like an app on your phone. Instead it should be thought of as a component of your web app that will contain the logic for displaying and connecting HTML documents.

Enter the mysite directory folder and create the main app of the project. manage.py is a Python script to execute different functions and startapp is the function we call to actually create our app. main is the arbitrary name we give to our Django app.

 

Run the development server from the CLI

macOS Terminal

(env)User-Macbook:mysite user$ python3 manage.py runserver 
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
February 26, 2019 - 09:54:26
Django version 2.1.15, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-C.

Windows Command Prompt

(env) C:\Users\Owner\Desktop\Code\env\mysite>py manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
February 26, 2019 - 09:54:26
Django version 2.1.15, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-C.

Now that you have created a Django project and app, it's time to run the server and see your project in a browser window. runserver is a function to establish a connection to your local device. Specifically the connection is an IP connection; it allows you to connect to an IP address, called 127.0.0.1, in your browser. This will act as your development server that only you can access. When your web app is finished, you will run the web app on a production server so anyone can access it. The Terminal or Command Prompt will display the development server address:

http://127.0.0.1:8000/

Copy and paste this URL into a new browser window. A web page with a rocket will appear stating Django is successfully installed.

Django Rocket

 

 

Quit the development server from the CLI

macOS Terminal

(env)User-Macbook:mysite user$ python3 manage.py runserver 
...

(Ctrl + C or command + c)

(env)User-Macbook:mysite user$

Windows Command Prompt

(env) C:\Users\Owner\desktop\code\env\mysite>py manage.py runserver
...

(Ctrl + C or command + c)

(env) C:\Users\Owner\desktop\code\env\mysite>

Quit the server with the keyboard command Ctrl + C for Windows and command + C for macOS. If you check the browser page http://127.0.0.1:8000/ where the web app is displayed and refresh the page, you should observe that the page cannot load since the server is not running.

No server running

 

Your project is successfully up and running so let's move on to configuring Python files to display HTML documents in your Django project!








4: Configuring Django


At this stage in the tutorial, you need an interactive development environment (IDE) to help edit the Python files you just created in your Django project. As programs dedicated to editing code, IDEs have tools such as auto-completion, highlighting, and code change tracking. Many popular options are available for download at no cost including Sublime Text, Atom, and Eclipse. 

 

Install Sublime

Download SublimeGIF

In this tutorial, we'll be using the free version of Sublime Text. Download the Sublime IDE by visiting their website at https://www.sublimetext.com/3  and selecting your version at the top of the page. 

Save Sublime on your Desktop so you can easily access it.

 

Open your Django project in Sublime

Sublime > env

Open env in SublimeGIF

Once downloaded, open Sublime Text then click File > Open Folder... in the upper left-hand corner.  Open the Desktop folder and then the code folder. Finally select the env folder and click Select Folder to open env in Sublime.

 

Create a templates folder for your HTML documents

env> mysite > main > (New Folder) templates > (New Folder) main  > (New File) home.html

Create home.html in SublimeGIF

Click on the mysite folder. Then click on the main folder. Right click on the main folder and click New Folder... to create a new folder. Name the folder templates, then click Enter

Click on the templates folder then right click on the folder and select New Folder... to create a new folder named main. Click Enter.

Click on the new main folder then right click on the folder and select New File to create a file named home.html.

 

Edit the home.html file

env > mysite > main > templates > main > home.html

<p>Hello world!</p>

Since you now know the basics of HTML, this should be relatively straightforward. Click on the home.html file and wrap Hello world! in paragraph tags in your web app's homepage. Sublime will autocomplete the closing tag once you type </ . To save a file, press Ctrl+ S for Windows and command + C for macOS.  Always remember to save after editing a file or you might get an error when running your server.

Edit home.html

 

Edit the Django settings.py file

env > mysite > mysite > settings.py

...

INSTALLED_APPS = [
    'main.apps.MainConfig',
    ...
]
...

Click on to the mysite folder in the mysite directory and open the settings.py file. Type the above code under INSTALLED_APPS. INSTALLED_APPS is a list that designates the enabled applications in the Django project. Packages that we install in the future will also need to be listed here. The code 'main.apps.MainConfig' connects the main app folder to the Django project. Without this line, your main app will not connect to your Django project. You'll get an error if you forget to do this. Save the file, Ctrl + S.

Django settings.py

 

Edit the Django mysite > urls.py file

env > mysite > mysite > urls.py

from django.contrib import admin
from django.urls import path, include  #add include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include ('main.urls')),   #add this
]

Enter the code above in the urls.py file to connect the main > urls.py file to the mysite > urls.py file. Save the file, Ctrl + S. In the previous step, we connected our main app to our mysite project. In this current step, we connect our main > urls.py file to mysite > urls.py. However, we still need to actually create the main > urls.py file that we are referencing.

from is necessary to specify where the module is located. In the example above, django.contrib or the [location of module] denotes the contrib folder inside the django folder, while django.urls denotes the urls folder inside the django folder. These folders are located inside env > Lib > site-packages. import precedes the module to be imported such as admin or path.  We import modules to use Django's pre-built features.

Editing mysite >urls.py

 

Creating the Django main > urls.py file

env > mysite > main > (New File) urls.py

Creating main > urls.pyGIF

Right click on the main folder in the sidebar and click New File to create a new file named urls.py.

 

 

Edit the main > urls.py file

env > mysite > main > urls.py

from django.urls import path
from . import views

app_name = "main"   


urlpatterns = [
    path("", views.homepage, name="homepage"),
]

Copy and paste the above code in the new urls.py file in the main folder. By creating this file and adding the code, you have just specified the name of the app is main and a URL path that connects to a homepage function. Save the file, Ctrl + S.

The quotations are left blank for the homepage URL pattern because the URL of the homepage will not have any text after the domain address.  The domain for the homepage will be http://127.0.0.1:8000/ instead of http://127.0.0.1:8000/homepage.  Don't worry if this part is confusing.  We will add plenty of URL paths to this file and the process will become more understandable. 

 

Configuring the views.py file

env > mysite > main > views.py

from django.shortcuts import render

# Create your views here.
def homepage(request):
	return render(request = request, template_name="main/home.html"	)

Open views.py and write a function called homepage that takes in a request and returns a render of the home.html file we created.  The request contains information about the user and needs to be included in all functions in views.py.  Since we referenced this function in urls.py, the function will run when we refresh our page in our browser. In this case, the home.html file in the main > templates folder will be rendered any time http://127.0.0.1:8000/ is requested. Save the changes to the file, Ctrl + S.

Sublime edit views.py

 

Migrate initial changes

macOS Terminal

(env)User-Macbook:mysite user$python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK

Windows Command Prompt

(env) C:\Users\Owner\Desktop\Code\env\mysite>py manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK

You may have noticed a message about unapplied migration(s) last time you ran your server.  Let's get rid of this warning by running the migrate command to apply migrations and create our database.  After running migrate the first time, we will only need to run this command again if we edit the models.py file since it directly links to our database.  

For reference, python3 or py is name of programming language we are using, manage.py is a folder containing a Python script to run commands for your project, and migrate applies the migrations or configuration updates to the database.

 

Viewing your new home.html file in the browser

macOS Terminal

(env)User-Macbook:mysite user$python3 manage.py runserver

Windows Command Prompt

(env) C:\Users\Owner\Desktop\Code\env\mysite>py manage.py runserver

Run the development server in the CLI again with python3 or py manage.py runserver and refresh the http://127.0.0.1:8000/ page in your browser to display the homepage. The homepage should now say "Hello world!" on a white page. Your Django project and app are now properly configured.

Django configured project in browser






Quiz Questions


1. How do you create a Django project after Django has been installed?


2. How do you run the development server?


3. What is the address of your local development server?


Next lesson


Check out the comments and debug buttons if you get stuck.