Django is a straightforward framework that facilitates the swift development of web applications. You can quickly create your first web application, which simply displays a Hello World
message by following some easy steps using the Django framework.
Step 1: Install Python
- Install Python 3.x from the official website. Click on download to get the latest version of Python. Make sure you select Add to PATH, so you can directly use it on Command Prompt.
- Confirm Python was installed correctly by opening a new Command Prompt/Powershell and then type the below command:
> python –-version
Python 3.10.2
Step 2: Create a Virtual Environment (Optional)
- You should use a dedicated virtual environment for each new Python project. Virtual environments allow you to create and manage separate environments for each Python project on the same computer.
- For example, Project A uses Django 2.2 but Project B uses Django 3.0. So by using the virtual environment, you can have two versions of Django on the same computer.
- To create a virtual environment with the name
myenv
, type the following command in the command prompt:
C:\> python -m venv c:\path\myenv
- Once created, a virtual environment must be activated with the command in the command prompt:
C:\> c:\path\myenv\Scripts\activate.bat
- Below are full commands to create and activate a new virtual environment called
myenv
.
C:\> python -m venv myenv
C:\> myenv\Scripts\Activate.bat
(myenv) >
- If you are in Powershell, then you need to use the following commands to create and activate the virtual environment.
C:\> python -m venv myenv
C:\> myenv\Scripts\Activate.ps1
(myenv) C:\>
- To deactivate and leave a virtual environment type
deactivate
.
(myenv) C:\> deactivate
C:\>
Step 3: Install Django
Now Python is installed and we know how to use virtual environments it is time to install Django for the first time.
Type the following command to install Django in your current virtual environments.
(myenv) C:\> pip install django
Step 4: Creating the First Project
Now you are ready to create a Django project. You can give any name to a Django project but I will use hello_world
in this tutorial. Use the below command to create a new Django project.
(myenv) C:\> django-admin startproject hello_world
New directories will be created in the current working directory. Let’s look at what startproject
created:
├ ── hello_world
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├ ── manage.py
└── myenv/
As you can see, within hello_world are five new files:
- __init__.py indicates that the files in the folder are part of a Python package. Without this file, we cannot import files from another directory which we will be doing a lot of in Django.
- asgi.py allows for an optional Asynchronous Server Gateway Interface to be run.
- settings.py controls our Django project’s overall settings
- urls.py tells Django which pages to build in response to a browser or URL request.
- wsgi.py stands for Web Server Gateway Interface which helps Django serve our eventual web pages.
The manage.py
file is not part of hello_world
but is used to execute various Django commands such as running the local web server or creating a new app.
Let’s change the directory to the newly created project folder.
(myenv) C:\> cd hello_world
Now let’s check if everything is working by running Django’s internal web server using the below runserver
command.
(myenv) C:\hello_world> python manage.py runserver
Don’t worry about 18 unapplied migrations. Visit http://127.0.0.1:8000/ in your web browser and make sure the following web page is visible:
If you can see the above web page then you have successfully created a project. If there is any error make sure you follow all steps mentioned above.
Step 5: Add App in hello_world Project
To add a new app go to the command line and quit the running server with CTRL+C. Then use the startapp
command followed by the name of our app which will be mysite
.
(myenv) C:\hello_world> python manage.py startapp mysite
If you look visually at the hello_world
directory Django has created within it a new mysite
directory containing the following files:
├── mysite
│ ├── migrations
│ │ └── __init__.py
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
Let’s review what each new mysite
app file does:
- admin.py is a configuration file for the built-in Django Admin app
- apps.py is a configuration file for the app itself
- migrations/ keep track of any changes to our
models.py
file so it stays in sync with our database - models.py is where we define our database models which Django automatically translates into database tables
- tests.py is for app-specific tests
- views.py is where we handle the request/response logic for our web app
Even though our new app exists within the Django project, Django doesn’t know about it until we explicitly add it to the hello_world/settings.py
file. In your text editor open the file up and scroll down to INSTALLED_APPS
where you’ll see six built-in Django apps already there. Add mysite.app.MysiteConfig
is at the bottom.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mysite.apps.MysiteConfig', #newly added
]
What is MysiteConfig
? Well, it is the name of the solitary function within the mysite/apps.py
file at this point.
from django.apps import AppConfig
class MysiteConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'mysite'
Step 6: Create the First View in mysite
App
The next step is to create our first view. Add the below code in the mysite/views.py
file:
# mysite/views.py
from django.shortcuts import HttpResponse
def index(request):
return HttpResponse("Hello, World!")
We’ve created a function called index
that accepts the request object and returns a response with the string “Hello, World!”.
Moving along we need to configure our URLs. In your text editor, create a new file called urls.py
within the mysite
app directory. Then add the following code:
# mysite/urls.py
from django.urls import path
from mysite import views
urlpatterns = [
path("", views.index, name="index"),
]
On the top line we import the path from Django to power our URL pattern and on the next line, we import our views. By referring to the views.py
file as views we are telling Django to look within the current directory for a views.py
file and import all views from there.
The last step is to update our hello_world/urls.py
file. It’s common to have multiple apps within a single Django project, like mysite
here, and they each need their own dedicated URL path.
# hello_world/urls.py
from django.contrib import admin
from django.urls import path, include # new
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("mysite.urls")), # new
]
We have written all the code we needed. To confirm everything works as expected, restart our Django server:
(myenv) C:\hello_world> python manage.py runserver
Open the URL http://127.0.0.1:8000, and you can see the “Hello, World!” text in your browser.
Recommended: How to Use Pagination in Django Application