First of all! 😀
Take a good look at this article, that will give you a quick grasp of what is Django, and why you should use it!
What is Django, and why you should use it 🐍
Daniel Diaz for Developer Road ・ Mar 1 '21
What you will learn 📖
Continuing with this article, here you will learn:
- Install Django, (and it's dependencies)
- Take a quick look at the Django Project structure.
- The basics of the MVT pattern
- Use the Django Template Language
Source code 💻
The source code of this tutorial is available in this Github repository:
Developer-road / django-hello-world
A simple Django hello world app
django-hello-world
A begginers hello world guide to the django web framework.
Install requirements:
python3 -venv .venv
source .venv/bin/activate
pip install -r requirements.txt
Installation 🐍
First of all, you have to install Python, which is one of the most loved languages in the world, and Django is built with it!
Check out the python downloads page
And install the Python 3 version for your operative system: Windows, Mac or Linux
Reminder: Most of Linux distributions, comes with Python Preinstalled so you don't have to worry about install it.
Terminal
Now it's time to use the terminal, or Command line interface
😨 . I know it can be scaring to use the terminal for the first time, but it is an essential skill, that I think every developer should have.
Depending in your operating system, you have different terminal emulators installed, so let's take a look of each terminal for Different OS.
Windows
In windows you have to preinstalled options, CMD
and Powershell
. Both are terrible 😂, but you can get the job done with them.
Note: In windows the file structure is different from UNIX based (Mac OS and Linux), so usually I recommend to install Git bash, that lets you to run the same commands I'll be using in this tutorial, but I let it up to you.
Mac OS and Linux
In these operative systems, you have built in terminals and you can search it directly in your programs search bar.
Also if you find too complex to use your system terminal, just use integrated terminals from different code editors
For example Vs Code
Verifying Python Installation
Now that you know to open up your terminal, let's check if we have Python installed
python --version
If I run this command I get:
Which means that the Python version. I have installed in my system is Python 3.8.6
.
Also check for pip
pip stands for PIP install packages
. It is a Python package manager, that will allow us to install different useful packages, included Django 😆
To check if pip installed, we use
pip --version
As you see, I have pip 20.3.3
installed
Installing Django
Before we can install Django, we should set up a virtual environment, to do that, we run
python -m .venv
This will create a Virtual environment with the name of .venv
.
If you want to know more about virtual environments, just take a look on this post.
🧠 Tutorial: Understand Virtual environments in Python ✅
Daniel Diaz for Developer Road ・ Feb 27 '21
Now activate that virtual environment 😀
source .venv/bin/activate
You can easily install Django, with a simple pip
command
pip install django
You will see something like this in your terminal
Lastly confirm your django installation
╰(.venv)─λ pip freeze 0 (0.003s) < 21:15:55
asgiref==3.3.1
Django==3.1.7
pytz==2021.1
sqlparse==0.4.1
As you see I installed Django 3.1.7
, which is the latest version of Django, in this moment.
Advice: I always recommend to use the latest django version, since it has the more patches and security fixes.
But if you are already working with a team, or for a company with an older Django version, you should continue using it.
Anyways the Django project team, had been doing an amazing job, because no matter if you learn the Django 3.x version, 2.x or even 1.x (Don't use it please 😆), most of the core functionality still the same.
Creating a project
To create a project in django, you will use the following command
django-admin startproject helloworld
This will create a folder name helloworld
, and inside that folder, there will be another folder named hellowold
, and a Python file manage.py
╰(.venv)─λ tree .
├── helloworld
│ ├── helloworld
│ │ ├── asgi.py
│ │ ├── __init__.py
│ │ ├── settings.py
│ │ ├── urls.py
│ │ └── wsgi.py
│ └── manage.py
I know this file structure could be confuse 😕, so I'll explain it in detail.
Django double folder structure
As you may notice, when you create a project in Django, there will be two folders named the same, but these two have differences.
The root folder /helloworld is just like a container, it doesn't matter for django, and it is only there for organization purposes.
You can rename it with whatever you want.
In the other hand there is the inside folder /helloworld/helloworld. It is a Python package since it has a __init__.py
.
We will use it to configure our Django project, and to import everything from other apps. (Later we'll see what is an app 😉).
Inside the helloworld
package, we can found another important files:
-
__init__.py
, indicates that the project folder must be considered as a package -
settings.py
, used to configure our app. -
urls.py
, lets you add or remove url patterns -
wsgi.py & asgi.py
, configure your deploy server
Finally the manage.py
file, is a command line utility that let us interact with the Django framework.
Running a development server.
To run a local server, run the following command
python manage.py runserver
You can specify a port for the server. So this time I'll use the port 8080, as an demonstration.
python manage.py runserver 8080
Note: You will see warning about migrations, but don't worry you will not manage them in this tutorial.
After running that command, go to your browser and type:
# Or the port you used in the runserver command
localhost:8080
After doing that, you should get a page like this, that confirms the installation
Ok, you got it. You installed your first Django project 🦄
Now let's go with the interesting part 😁
Using the MVT pattern
Before continue, I want to tell you about the MVT pattern or Model, View, Template. I know that it sounds confusing, but please don't turn off your brain 🧠, and don't give up 👏.
First of all, why Django uses this pattern? 💭
Django uses this pattern, because it allows the developer, to skip the tedious part of creating a custom controller.
Now, let's get into the different parts of this design pattern:
-
Model:
Holds all of the logical structure of your database. It manages all of the operations, in the database, like creating, updating and deleting.
Due to the models, we as Django Developers mustn't learn SQL 💽 (although it would be a good plus).
-
View:
As a quick definition, a view receives a request, and return a response. Usually the view receives a HTTP response, likeGET
, and return a html file, or a Json file, or nearly everything.
That return of html files, is called *Template *.
-
Template:
Is what is shown to the user, if everything results Ok with his/her request. It acts as a presentation layer, and you can write them with html, css, javascript, and a special language: The Django template language.
These templates, are designed to "Don't repeat yourself", since Django uses a special language DTL
, to build them.
Creating the hello world app
Since this is a beginners guide, we will only use, Urls, Views and templates 😉.
Creating an app
Before continuing, we're going to create a django app.
django-admin startapp myapp
Our app is called myapp
, and it contains several files and a strange folder named migrations
😮.
Let's take a look at the structure of our app.
. myapp/
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
1 directory, 7 files
admin.py :
Here we can register our models in the admin page (We will see it in next articles)tests.py :
This file is where we make our unit tests.models.py :
Where we create our models, and where we interact with our databaseapps.py :
Configuration of our app. I've never touch it 😅views.py :
All of our business logic lives here. This file contains the views that will render our templates./migrations :
Here is where migrations live. I'll create a post about it, but as a quick concept a migration is a recording of the changes of our models.
Differences app and a Project
Do you remember that we already created a project, called helloworld
?.
Well now we just created an app, and here are the differences.
Project | App |
---|---|
Collections of apps, for a website | Web application that does something |
Can contain multiple apps | Can be in multiple projects |
Ex: A Blog website | Ex: A comments app that can be in many projects, like Disqus |
Until now, we haven't touched any code, so let's get into it.
Hands on 🙌
Installing our app:
We just created an app, so let's install it in the settings.py
file
# helloworld/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Custom apps
'myapp',
]
After installed our new app, we can get into url patterns.
Go to the urls.py
file, in our project folder and modify the following things.
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# The url path of our new app
path('', include('myapp.urls')),
]
Here we imported the function include
, that as the name suggests include the url patterns of external apps 😀.
Then we created another path
, with the destination of ''
, that means that when a user hits the url, without any other pattern, we call the urls of the app myapp
As you may noticed, we are calling the urls as a Python package, so myapp.urls
means:
- Go to the
myapp
package - Extract the url patterns of the
urls.py
file.
But you would say me: Daniel! are you crazy 🤯, that file hasn't been created.
And yeah, you are right. So we need to create it manually.
You can create it from your code editor, or from your terminal
cd myapp/
touch urls.py
After creating that file, we are going to made the fun stuff! 😝
Creating our first view:
Let's edit our views.py
file.
from django.http import HttpResponse
# Create your views here.
def helloworldview(request):
response = "Hello world, this is my first Django app! :)"
return HttpResponse(response)
Here we imported the HttpResponse class and we passed a variable response
, with a value of: "Hello world .."
Ok cool, but next we have to create an url for that view, let's go to the myapp/urls.py
file.
from django.urls import path
from .views import helloworldview
urlpatterns = [
path("", helloworld),
]
As in the urls.py of the project folder, we imported path
, and created url patterns for our app. Also we used a new concept, we passed a view to our path function.
All of the stuff we just do, means that each time that we hit localhost:8000
, we request the url pattern of ""
.
That url will call our view function named helloworldview
, that takes our request
, and returns a HttpResponse
, with the content of "Hello world".
Not that hard to understand, right 😅?
Now run the server, and watch your first app working!
python manage.py runserver
# See it on localhost:8000
Using Django templates
The last part of this tutorial will be about, Templates in Django 😀
First of all a Django template, is a html document, that uses the Django template language, to incorporate data and logic on our front end.
Your first template in Django
Before using templates, we need to create a folder in our app to be able to use it.
So let's create one:
cd myapp/
mkdir templates
You just created a directory, named templates
. That tells Django to search for templates in that folder.
Create a file, named index.html
, that will be our first template.
touch index.html
Now, paste the following html, in the template.
<h1>Hello world, this is my first template</h1>
<p>This is a cool html paragraph!</p>
After that we are going to modify the helloworldview
, in order to render our template
from django.shortcuts import render
def helloworldview(request):
template = "index.html"
context = {}
return render(request, template, context)
Here, we used the function render, that takes as parameters, the user request, the name of the template, in this case index.html
, and the context, that we will see how to use it later.
After that minor changes, you'll see something like this.
Using the DTL
Now we will see the basics of Django template language.
Create a file base.html
, inside the templates folder.
touch base.html
There we will paste the basic structure of a html Document.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Django Hello world</title>
</head>
<body>
{% block body %}
{% endblock body %}
</body>
</html>
But with a little change we are using DTL tags. Those are of the shape {% tag %}
. The tag we used in this case, is:
{% block [name of the block] %}
{% endblock [name of the block] %}
That tags, allow us to put html code, in block codes, as we are going to see now.
Template inheritance 😁
Now modify, the index.html
file.
{% extends 'base.html' %}
{% block body %}
<h1>Hello world, this is my first template</h1>
<p>This is a cool html paragraph!</p>
{% endblock body %}
Here we just do a strange thing! 🤯, we used template inheritance, and DTL blocks.
You call, the inheritance with the tag {% extends "name of template" %}
And with the block tag you replace the content inside the block
{% block [name of block] %}
... Replaced content
{% endblock [name of block] %}
If we look at the source page of our page, we get something like this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Django Hello world</title>
</head>
<body>
<h1>Hello world, this is my first template</h1>
<p>This is a cool html paragraph!</p>
</body>
</html>
Context variables and for loops
We are going to pass context variables from our views. so let's modify the view
def helloworldview(request):
template = "index.html"
people = ["daniel", "nicolas", "tom", "henry"]
context = {"people": people}
return render(request, template, context)
We are passing, a context dictionary to our template. Our key "people" is a list of strings.
Now we are going to make a for loop, to iterate through that list 😁.
{% extends 'base.html' %}
{% block body %}
<h1>Hello world, this is my first template</h1>
<p>This is a cool html paragraph!</p>
{% for person in people %}
<p>{{person}}</p>
{% endfor %}
{% endblock body %}
As you may notice, the for loops in DTL are exactly the same as they are in Python.
And variables, in DTL are represented with {{ name_variable }}
If we check our server, we'll get something like
this. 🤯
Amazing, it isn't ?
Conclusion:
In this tutorial, you learned the basics of django.
From creating function based views, to building url patterns and using the Django template language 😃.
Any questions or doubts ? Let me know in the comments
Follow me in My blog,
to get more awesome tutorials like this one.
Please consider supporting me on Ko-fi you help me a lot to
continue building this tutorials!.
Top comments (1)
Any question? Let me know!