Django Requires Python
To check
if your system has Python installed, run this command in the command prompt:
python --version
If Python
is installed, you will get a result with the version number, like this
Python 3.9.2
If you
find that you do not have Python installed on your computer, then you can
download it for free from the following website: https://www.python.org/
PIP
To
install Django, you must use a package manager like PIP, which is included in
Python from version 3.4.
To check
if your system has PIP installed, run this command in the command prompt:
pip --version
If PIP is
installed, you will get a result with the version number.
For me,
on a windows machine, the result looks like this:
pip 20.2.3 from
c:\python39\lib\site-packages\pip (python 3.9)
If you do
not have PIP installed, you can download and install it from this page: https://pypi.org/project/pip/
Virtual Environment
It is
suggested to have a dedicated virtual environment for each Django project, and
one way to manage a virtual environment is venv, which is included
in Python.
The name
of the virtual environment is your choice, in this tutorial we will call
it myworld.
Type the
following in the command prompt, remember to navigate to where you want to
create your project:
Windows:
py -m venv myworld
Unix/MacOS:
python -m venv myworld
This will
set up a virtual environment, and create a folder named "myworld"
with subfolders and files, like this:
myworld
Include
Lib
Scripts
pyvenv.cfg
Then you
have to activate the environment, by typing this command:
Windows:
myworld\Scripts\activate.bat
Unix/MacOS:
source myworld/bin/activate
Once the
environment is activated, you will see this result in the command prompt:
Windows:
(myworld) C:\Users\Your Name>
Unix/MacOS:
(myworld) ... $
Django is
installed using pip, with this command:
Windows:
(myworld) C:\Users\Your Name>py -m pip install
Django
Unix/MacOS:
(myworld) ... $ python
-m pip install Django
Which
will give a result that looks like this (at least on my Windows machine):
Collecting Django
Downloading Django-4.0.3-py3-none-any.whl (8.0 MB)
|████████████████████████████████| 8.0 MB 2.2
MB/s
Collecting sqlparse>=0.2.2
Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB)
Collecting asgiref<4,>=3.4.1
Downloading asgiref-3.5.0-py3-none-any.whl (22 kB)
Collecting tzdata; sys_platform == "win32"
Downloading tzdata-2021.5-py2.py3-none-any.whl (339 kB)
|████████████████████████████████| 339 kB 6.4
MB/s
Installing collected packages: sqlparse, asgiref, tzdata, Django
Successfully installed Django-4.0.3 asgiref-3.5.0 sqlparse-0.4.2 tzdata-2021.5
WARNING:
You are using pip version 20.2.3; however, version 22.3 is available.
You should consider upgrading via the 'C:\Users\Your Name\myworld\Scripts\python.exe -m pip install --upgrade pip'
command.
That's
it! Now you have installed Django in your new project, running in a virtual
environment!
Windows, Mac, or Unix?
You can
run this project on either one. There are some small differences, like when
writing commands in the command prompt, Windows uses py as
the first word in the command line, while Unix and MacOS use python:
Windows:
py --version
Unix/MacOS:
python --version
Check Django Version
You can
check if Django is installed by asking for its version number like this:
(myworld) C:\Users\Your Name>django-admin --version
If Django
is installed, you will get a result with the version number:
4.1.2
My First Project
Once you
have come up with a suitable name for your Django project, like mine: my_tennis_club,
navigate to where in the file system you want to store the code (in the virtual
environment), I will navigate to the myworld folder, and run this command in the command prompt:
django-admin startproject
my_tennis_club
Django
creates a my_tennis_club folder
on my computer, with this content:
my_tennis_club
manage.py
my_tennis_club/
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
These are
all files and folders with a specific meaning, you will learn about some of
them later in this tutorial, but for now, it is more important to know that
this is the location of your project, and that you can start building applications
in it.
Run the Django Project
Now that
you have a Django project, you can run it, and see what it looks like in a
browser.
Navigate
to the /my_tennis_club folder
and execute this command in the command prompt:
py manage.py runserver
Which
will produce this result:
Watching for file changes
with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 18 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.
October 27, 2022 - 13:03:14
Django version 4.1.2, using settings 'my_tennis_club.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Open a
new browser window and type 127.0.0.1:8000 in the address bar.
Create App
I will
name my app members.
Start by
navigating to the selected location where you want to store the app, in my case
the my_tennis_club folder,
and run the command below.
If the
server is still running, and you are not able to write commands, press [CTRL]
[BREAK], or [CTRL] [C] to stop the server and you should be back in the virtual
environment.
py manage.py startapp
members
Django
creates a folder named members in my project, with this content:
my_tennis_club
manage.py
my_tennis_club/
members/
migrations/
__init__.py
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
These are
all files and folders with a specific meaning. You will learn about most of
them later in this tutorial.
First,
take a look at the file called views.py.
This is
where we gather the information we need to send back a proper response.
Views
Django
views are Python functions that take http requests and return http response,
like HTML documents.
A web
page that uses Django is full of views with different tasks and missions.
Views are
usually put in a file called views.py located on your app's folder.
There is
a views.py in
your members folder
that looks like this:
my_tennis_club/members/views.py:
from django.shortcuts import render
# Create your views here.
Find it
and open it, and replace the content with this:
my_tennis_club/members/views.py:
from django.shortcuts import render
from django.http import HttpResponse
def members(request):
return HttpResponse("Hello world!")
Note: The name of the view does not have to be the same as the
application.
I call
it members because
I think it fits well in this context.
This is a
simple example on how to send a response back to the browser.
But how
can we execute the view? Well, we must call the view via a URL.
URLs
Create a
file named urls.py in
the same folder as the views.py file, and type this code in it:
my_tennis_club/members/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('members/', views.members, name='members'),
]
The urls.py file
you just created is specific for the members application. We have to do some routing in the root
directory my_tennis_club as
well. This may seem complicated, but for now, just follow the instructions
below.
There is
a file called urls.py on
the my_tennis_club folder,
open that file and add the include module in the import statement, and also add a path() function
in the urlpatterns[] list,
with arguments that will route users that comes in via 127.0.0.1:8000/.
Then your
file will look like this:
my_tennis_club/my_tennis_club/urls.py:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('members.urls')),
path('admin/', admin.site.urls),
]
If the
server is not running, navigate to the /my_tennis_club folder and execute this command in the
command prompt:
py manage.py runserver
In the
browser window, type 127.0.0.1:8000/members/ in
the address bar.
Templates
In
the Django Intro page,
we learned that the result should be in HTML, and it should be created in a
template, so let's do that.
Create
a templates folder
inside the members folder,
and create a HTML file named myfirst.html.
The file
structure should be like this:
my_tennis_club
manage.py
my_tennis_club/
members/
templates/
myfirst.html
Open the
HTML file and insert the following:
my_tennis_club/members/templates/myfirst.html:
<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
<p>Welcome to my first Django
project!</p>
</body>
</html>
Modify the View
Open
the views.py file
and replace the members view
with this:
my_tennis_club/members/views.py:
from django.http import HttpResponse
from django.template import loader
def members(request):
template = loader.get_template('myfirst.html')
return HttpResponse(template.render())
Change Settings
To be
able to work with more complicated stuff than "Hello World!", We have
to tell Django that a new app is created.
This is
done in the settings.py file
in the my_tennis_club folder.
Look up
the INSTALLED_APPS[] list
and add the members app
like this:
my_tennis_club/my_tennis_club/settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'members'
]
Then run
this command:
py manage.py migrate
Which
will produce this output:
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 auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
(myworld) C:\Users\Your Name\myworld\my_tennis_club>
Start the
server by navigating to the /my_tennis_club folder and execute this command:
py manage.py runserver
In the
browser window, type 127.0.0.1:8000/members/ in
the address bar.
The
result should look like this:
Templates
In
the Django Intro page,
we learned that the result should be in HTML, and it should be created in a
template, so let's do that.
Create
a templates folder
inside the members folder,
and create a HTML file named myfirst.html.
The file
structure should be like this:
my_tennis_club
manage.py
my_tennis_club/
members/
templates/
myfirst.html
Open the
HTML file and insert the following:
my_tennis_club/members/templates/myfirst.html:
<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
<p>Welcome to my first Django
project!</p>
</body>
</html>
Modify the View
Open
the views.py file
and replace the members view
with this:
my_tennis_club/members/views.py:
from django.http import HttpResponse
from django.template import loader
def members(request):
template = loader.get_template('myfirst.html')
return HttpResponse(template.render())
Change Settings
To be
able to work with more complicated stuff than "Hello World!", We have
to tell Django that a new app is created.
This is
done in the settings.py file
in the my_tennis_club folder.
Look up
the INSTALLED_APPS[] list
and add the members app
like this:
my_tennis_club/my_tennis_club/settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'members'
]
Then run
this command:
py manage.py migrate
Which
will produce this output:
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 auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
(myworld) C:\Users\Your Name\myworld\my_tennis_club>
Start the
server by navigating to the /my_tennis_club folder and execute this command:
py manage.py runserver
In the
browser window, type 127.0.0.1:8000/members/ in
the address bar.
The
result should look like this:
Wonderful Article. Thanks for sharing this post
ReplyDeleteDBT Training
DBT Online Training
DBT Classes Online
DBT Training Courses
Best Online DBT Courses
DBT Certification Training Online
Data Build Tool Training in Hyderabad
Best DBT Course in Hyderabad
Data Build Tool Training in Ameerpet
It is an informative and good article. Thanks for sharing.
ReplyDeleteSite Reliability Engineering Training
SRE Course
Site Reliability Engineering Online Training
SRE Training Online
Site Reliability Engineering Training in Hyderabad
SRE Online Training in Hyderabad
SRE Courses Online
SRE Certification Course
It is an informative and good article. Thanks for sharing.
ReplyDeleteSite Reliability Engineering Training
SRE Course
Site Reliability Engineering Online Training
SRE Training Online
Site Reliability Engineering Training in Hyderabad
SRE Online Training in Hyderabad
SRE Courses Online
SRE Certification Course
Helms Portal offers an advanced SaaS LMS to revolutionize online education and training. saas learning management system . It supports course delivery, learner tracking, and performance analysis with ease. Whether for academic institutions or businesses, Helms Portal is designed to scale and adapt to diverse needs
ReplyDelete