Introduction to Django
Introduction to Django
Django
Django is a back-end server side web framework.
The most common way to extract data from a database is SQL. One problem
with SQL is that you have a pretty good understanding of the database
structure to be able to work with it.
<h1>My Homepage</h1>
<p>My name is {{ firstname }}.</p>
When you have installed Django and created your first Django web
application, and the browser requests the URL, this is basically what happens:
1.Django receives the URL, checks the urls.py file, and calls the view that
matches the URL.
2.The view, located in views.py, checks for relevant models.
3.The models are imported from the models.py file.
4.The view then sends the data to a specified template in the templates folder.
5.The template contains HTML and Django tags, and with the data it returns
finished HTML content back to the browser.
Django can do a lot more than this and are the basic steps in a simple web
application made with Django.
Django Getting Started
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.13.2
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 24.3.1 from C:m Files\WindowsApps\PythonVersion\Lib\site-packages\pip (python 3.13)
Django - Create Virtual Environment
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, we will call it myworld.
Type the following in the command prompt, remember to navigate to where you want to create your
project:
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
.gitignore
pyvenv.cfg
Then you have to activate the environment, by typing this command:
myworld\Scripts\activate.bat
Once the environment is activated, you will see this result in the command prompt :
(myworld) C:\Users\Your Name>
Install Django
• Now, that we have created a virtual environment, we are ready
to install Django.
python -m pip install Django
Check Django Version
my_tennis_club
manage.py
my_tennis_club/
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
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:
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.
March 19, 2025 - 14:19:38
Django version 5.1.7, 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.
Django Create App
• An app is a web application that has a specific meaning in your project, like a home page, a contact form, or
a members database.
let's just create a simple Django app that displays "Hello World!".
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.
python 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
Django 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!")
This is a simple example on how to send a response back to the
browser.
Django URLs my_tennis_club/my_tennis_club/urls.py:
Create a file named urls.py in the same from django.contrib import admin
folder as the views.py file, and type this from django.urls import include, path
code in it: urlpatterns = [ path('',
my_tennis_club/members/urls.py: include('members.urls')), path('admin/',
from django.urls import path
from . import views urlpatterns = [ admin.site.urls), ]
path('members/', views.members,
name='members’),
]
The urls.py file you just created is
specific for the members application. We If the server is not running, navigate to
have to do some routing in the root the /my_tennis_club folder and execute
directory my_tennis_club as well. This may this command in the command prompt:
seem complicated, but for now, just follow python manage.py runserver
the instructions below. In the browser window, type
There is a file called urls.py on 127.0.0.1:8000/members/ in the address
the my_tennis_club folder, open that file and bar.
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/.
Modify the View
Django Templates Open the views.py file in
the members folder, and replace its content
Create a templates folder inside with this:
the members folder, and create a HTML file my_tennis_club/members/views.py:
named myfirst.html.
from django.http import HttpResponse
The file structure should be like this: from django.template import loader
my_tennis_club def members(request):
manage.py template =
loader.get_template('myfirst.html’)
my_tennis_club/ return HttpResponse(template.render())
members/ Change Settings
To be able to work with more complicated stuff than "Hello
templates/
World!", We have to tell Django that a new app is created.
myfirst.html This is done in the settings.py file in
the my_tennis_club folder.
my_tennis_club/members/ Look up the INSTALLED_APPS[] list and add the members app like
templates/myfirst.html: this:
my_tennis_club/my_tennis_club/
<!DOCTYPE html> settings.py:
<html> INSTALLED_APPS = [
'django.contrib.admin’,
<body> 'django.contrib.auth’,
<h1>Hello World!</h1> 'django.contrib.contenttypes’,
<p>Welcome to my first Django project! 'django.contrib.sessions’,
</p> 'django.contrib.messages’,
</body> 'django.contrib.staticfiles’,
</html> 'members’
]
Then run this command:
python manage.py migrate
Start the server by navigating to the /my_tennis_club folder and
execute this command:
python manage.py runserver
In the browser window, type 127.0.0.1:8000/members/ in the address
bar.
Django Models
• A Django model is a table in your database.
• Now we will see how Django allows us to work with data, without having to
change or upload files in the process.
• In Django, data is created in objects, called Models, and is actually tables in a
database.
Create Table (Model)
To create a model, navigate to the models.py file in the /members/ folder.
Open it, and add a Member table by creating a Member class, and describe the table
fields in it:
my_tennis_club/members/models.py:
from django.db import models
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
SQLite Database
When we created the Django project, we got an empty SQLite database.
It was created in the my_tennis_club root folder, and has the filename db.sqlite3.
By default, all Models created in the Django project will be created as tables in this database.
Django creates a file describing the changes
Migrate and stores the file in the /migrations/ folder:
my_tennis_club/members/migrations/
Now when we have described a Model in
0001_initial.py:
the models.py file, we must run a # Generated by Django 5.1.7 on 2025-03-29 11:39
command to actually create the table in from django.db import migrations, models
the database. class Migration(migrations.Migration):
initial = True
Navigate to the /my_tennis_club/ folder
dependencies = [
and run this command: ]
operations = [
python manage.py makemigrations migrations.CreateModel(
name='Member’,
members fields=[
('id',
Which will result in this output: models.BigAutoField(auto_created=True,
primary_key=True, serialize=False,
Migrations for 'members': verbose_name='ID')),
('firstname',
members\migrations\0001_initial.py models.CharField(max_length=255)),
- Create model Member ('lastname',
models.CharField(max_length=255)),
(myworld) C:\Users\Your Name\myworld\ ],
),
my_tennis_club> ]
Django inserts an id field for your tables, which is an auto increment number (first record gets the
value 1, the second record 2 etc.), this is the default behavior of Django, you can override it by
describing your own id field.
The table is not created yet, you will have to run one more command, then Django will create and
execute an SQL statement, based on the content of the new file in the /migrations/ folder.
you will see that there are 6 members in the Member table:
Update Records
To update records that are already in the database, we first
have to get the record we want to update:
>>> from members.models import Member
>>> x = Member.objects.all()[4]
x will now represent the member at index 4, which is "Stale
Refsnes", but to make sure, let us see if that is correct:
>>> x.firstname
This should give you this result:
'Stale'
Now we can change the values of this record:
>>> x.firstname = "Stalikken"
>>> x.save()
Execute this command to see if the Member table got updated:
>>> Member.objects.all().values()
Delete Records
To delete a record in a table, start by getting the record you
want to delete:
>>> from members.models import Member
>>> x = Member.objects.all()[5]
x will now represent the member at index 5, which is "Jane Doe",
but to make sure, let us see if that is correct:
>>> x.firstname
This should give you this result:
'Jane'
Now we can delete the record:
>>> x.delete()
The result will be:
(1, {'members.Member': 1})
How to create a form using Django Forms ?
# creating a form
class InputForm(forms.Form):
Cookies are essential for maintaining user sessions and preferences. They are used to store data such as login
information or user settings. Django provides easy methods to work with cookies, allowing to set and retrieve
them as needed.
def set_cookie_view(request):
response.set_cookie('my_cookie', 'cookie_value’)
return response