Install Django
Install Django
Django is installed using pip, with this command:
Windows:
(myworld) C:\Users\Your Name> py -m pip install Django
Unix/MacOS:
python -m pip install Django
(myworld) ... $
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
Windows, Mac, or Unix?
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
In the rest of this tutorial, we will be using the Windows command.
Check Django Version
You can check if Django is installed by asking for its version number like this:
django-admin --version
(myworld) C:\Users\Your Name>
If Django is installed, you will get a result with the version number: 4.1.2
Dark code
HTML CSS JAVASCRIPT Tutorials References Exercises Menu
Upgrade Get Certified Create Website Log in
Django Create Project
❮ Previous Next ❯
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 Dark code
HTML CSS JAVASCRIPT 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.
Dark code
HTML CSS JAVASCRIPT Open a new browser window and type 127.0.0.1:8000 in
the address bar.
The result:
What's Next?
We have a Django project!
The next step is to make an app in your project.
You cannot have a web page created with Django without an app. ❮ Previous Next ❯
ADVERTISEMENT
Django Admin Interface
Django provides a built-in admin module which can be used to perform CRUD
operations on the models. It reads metadata from the model to provide a quick
interface where the user can manage the content of the application.
This is a built-in module and designed to perform admin related tasks to the user. Let's
see how to activate and use Django's admin module (interface).
The admin app (django.contrib.admin) is enabled by default and already added into
INSTALLED_APPS section of the settings file.
To access it at browser use '/admin/' at a local machine like localhost:8000/admin/ and
it shows the following output:
It prompts for login credentials if no password is created yet, use the following command to
create a user.
Create an Admin User
$ python3 managen.py createsuperuser
Now start development server and access admin login.
$ python3 manage.py runserver
Provide created username and password and login.
After login successfully, it shows the following interface.
It is a Django Admin Dashboard. Here, we can add and update the registered models. The model
registration process will be discussed in further chapters.
← Prev Next →
Youtube
For Videos Join Our Youtube Channel: Join Now
Django URLs
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.
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.
Darkcode
HTMLCSSJAVASCRIPT
Django Views
Views
Django views are Python functions that takes http requests and returns 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.
Django Templates
Django provides a convenient way to generate dynamic HTML pages by using its template system.
A template consists of static parts of the desired HTML output as well as some special syntax
describing how dynamic content will be inserted.
Why Django Template?
In HTML file, we can't write python code because the code is only interpreted by python
interpreter not the browser. We know that HTML is a static markup language, while Python is a
dynamic programming language.
Django template engine is used to separate the design from the python code and allows us to
build dynamic web pages.
Django Template Configuration
To configure the template system, we have to provide some entries in settings.py file.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'django.template.context_processors.reques
'context_processors': [
t',
'django.template.context_processors.debug'
Skip Ad
,
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Here, we mentioned that our template directory name is templates. By default,
DjangoTemplates looks for a templates subdirectory in each of the INSTALLED_APPS.
Django Template Simple Example
First, create a directory templates inside the project app as we did below.
After that create a template index.html inside the created folder.
Skip Ad
Our template index.html contains the following code.
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h2>Welcome to Django!!!</h2>
</body>
</html>
Loading Template
To load the template, call get_template() method as we did below and pass template name.
//views.py
Skip Ad
from django.shortcuts import render
#importing loading from django template
from django.template import loader
# Create your views here.
from django.http import HttpResponse
def index(request):
template = loader.get_template('index.html') # getting our template
return HttpResponse(template.render()) # rendering the template in HttpResponse
Set a URL to access the template from the browser.
//urls.py
path('index/', views.index),
Register app inside the INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp'
]
Skip Ad
Run Server
Execute the following command and access the template by entering
localhost:8000/index at the browser.
$ python3 manage.py runserver
Django Template Language
Django template uses its own syntax to deal with variable, tags, expressions etc. A
template is rendered with a context which is used to get value at a web page. See the
examples.
Skip Ad
Variables
Variables associated with a context can be accessed by {{}} (double curly braces). For example, a
variable name value is rahul. Then the following statement will replace name with its value.
My name is {{name}}.
My name is rahul
Django Variable Example
//views.py
from django.shortcuts import render
#importing loading from django template
from django.template import loader
# Create your views here.
from django.http import HttpResponse
def index(request):
template = loader.get_template('index.html') # getting our template
name = {
'student':'rahul'
}
return HttpResponse(template.render(name)) # rendering the template in HttpResponse
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title> </head> Skip Ad
<body>
<h2>Welcome to Django!!!</h2>
<h3>My Name is: {{ student }}</h3>
</body>
</html>
Output:
Tags
In a template, Tags provide arbitrary logic in the rendering process. For example, a tag can output
content, serve as a control structure e.g. an "if" statement or a "for" loop, grab content from a
database etc.
Tags are surrounded by {% %} braces. For example.
{% csrf_token %}
{% if user.is_authenticated %}
Hello, {{ user.username }}.
{% endif %}
Skip Ad
← Prev Next →