0% found this document useful (0 votes)
24 views16 pages

Unit 5

Django is a Python framework designed to simplify web development by handling complex tasks, allowing developers to focus on building applications. It follows the MVT design pattern and emphasizes reusability through components, providing built-in features like a login system and database connections. The document outlines how to install Django, create projects and apps, define models, and perform CRUD operations using Django's ORM.

Uploaded by

disecek477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views16 pages

Unit 5

Django is a Python framework designed to simplify web development by handling complex tasks, allowing developers to focus on building applications. It follows the MVT design pattern and emphasizes reusability through components, providing built-in features like a login system and database connections. The document outlines how to install Django, create projects and apps, define models, and perform CRUD operations using Django's ORM.

Uploaded by

disecek477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

What is Django?

Django is a Python framework that makes it easier to create web sites using
Python.

Django takes care of the difficult stuff so that you can concentrate on building
your web applications.

Django emphasizes reusability of components, also referred to as DRY (Don't


Repeat Yourself), and comes with ready-to-use features like login system,
database connection and CRUD operations (Create Read Update Delete).

How does Django Work?


Django follows the MVT design pattern (Model View Template).

 Model - The data you want to present, usually data from a database.
 View - A request handler that returns the relevant template and content -
based on the request from the user.
 Template - A text file (like an HTML file) containing the layout of the web
page, with logic on how to display the data.

Model
The model provides data from the database.

In Django, the data is delivered as an Object Relational Mapping (ORM), which


is a technique designed to make it easier to work with databases.

The most common way to extract data from a database is SQL. One problem
with SQL is that you have to have a pretty good understanding of the database
structure to be able to work with it.

Django, with ORM, makes it easier to communicate with the database, without
having to write complex SQL statements.

The models are usually located in a file called models.py.


View
A view is a function or method that takes http requests as arguments, imports
the relevant model(s), and finds out what data to send to the template, and
returns the final result.

The views are usually located in a file called views.py.

Template
A template is a file where you describe how the result should be represented.

Templates are often .html files, with HTML code describing the layout of a web
page, but it can also be in other file formats to present other results, but we will
concentrate on .html files.

Django uses standard HTML to describe the layout, but uses Django tags to add
logic:

<h1>My Homepage</h1>

<p>My name is {{ firstname }}.</p>

The templates of an application is located in a folder named templates.

URLs
Django also provides a way to navigate around the different pages in a website.

When a user requests a URL, Django decides which view it will send it to.

This is done in a file called urls.py.


Install Django
pip install Django

Django Create Project


django-admin startproject testproject
testproject
manage.py
testproject/
__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.

py manage.py runserver

Open a new browser window and type 127.0.0.1:8000 in the address bar.

The result:
Django Create App
What is an 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.

In this tutorial we will create an app that allows us to list and register members
in a database.

But first, let's just create a simple Django app that displays "Hello World!".

I will name my app members.

Start by navigating to the selected location where you want to store the app, in
my case the testproject 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

testroject
manage.py
testproject/
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.
Django Views
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:

testproject/members/views.py:

from django.shortcuts import render

# Create your views here.

testproject/members/views.py:

from django.shortcuts import render

from django.http import HttpResponse

def members(request):

return HttpResponse("Hello world!")

Django URLs
URLs
Create a file named urls.py in the same folder as the views.py file, and type
this code in it:

testprojct/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 testproject as well. This may
seem complicated, but for now, just follow the instructions below.

There is a file called urls.py on the testproject 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:

testproject/testproject/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 /testproject 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.

Django Templates
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:

testproject
manage.py
testproject/
members/
templates/
myfirst.html

Open the HTML file and insert the following:

testproject/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:

testproject/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 testproject folder.

Look up the INSTALLED_APPS[] list and add the members app like this:
testproject/testproject/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

Django Models
Django Models
Up until now in this tutorial, output has been static data from Python or HTML
templates.

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:

testproject/members/models.py:

from django.db import models

class Member(models.Model):

firstname = models.CharField(max_length=255)

lastname = models.CharField(max_length=255)

The first field, firstname, is a Text field, and will contain the first name of the
members.

The second field, lastname, is also a Text field, with the member's last name.

Both firstname and lastname is set up to have a maximum of 255 characters.

SQLite Database
When we created the Django project, we got an empty SQLite database.

It was created in the testproject 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.

Migrate
Now when we have described a Model in the models.py file, we must run a
command to actually create the table in the database.
Navigate to the /testproject/ folder and run this command:

py manage.py makemigrations members

Which will result in this output:

Migrations for 'members':


members\migrations\0001_initial.py
- Create model Member

(myworld) C:\Users\Your Name\myworld\testproject>

Django creates a file describing the changes and stores the file in
the /migrations/ folder:

testproject/members/migrations/0001_initial.py :

from django.db import migrations, models

class Migration(migrations.Migration):

initial = True

dependencies = [

operations = [

migrations.CreateModel(

name='Member',

fields=[

('id', models.BigAutoField(auto_created=True,
primary_key=True, serialize=False, verbose_name='ID')),
('firstname', models.CharField(max_length=255)),

('lastname', models.CharField(max_length=255)),

],

),

Note that 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.

Run the migrate command:

py manage.py migrate

View SQL
As a side-note: you can view the SQL statement that were executed from the
migration above. All you have to do is to run this command, with the migration
number:

py manage.py sqlmigrate members 0001

Which will result in this output:

BEGIN;
--
-- Create model Member
--
CREATE TABLE "members_member" ("id" integer NOT NULL PRIMARY KEY
AUTOINCREMENT, "firstname" varchar(255) NOT NULL, "lastname" varchar(255)
NOT NULL); COMMIT;
Django Insert Data
Add Records
We will use the Python interpreter (Python shell) to add some members to it.

To open a Python shell, type this command:

py manage.py shell

Now we are in the shell, the result should be something like this:

Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64


bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

At the bottom, after the three >>> write the following:

>>> from members.models import Member

Hit [enter] and write this to look at the empty Member table:

>>> Member.objects.all()

This should give you an empty QuerySet object, like this:

<QuerySet []>

A QuerySet is a collection of data from a database.

Read more about QuerySets in the Django QuerySet chapter.

Add a record to the table, by executing these two lines:

>>> member = Member(firstname=test', lastname='test')


>>> member.save()

Execute this command to see if the Member table got a member:

>>> Member.objects.all().values()
Hopefully, the result will look like this:

<QuerySet [{'id': 1, 'firstname': 'raj', 'lastname': 'test'}]>

Add Multiple Records


You can add multiple records by making a list of Member objects, and
execute .save() on each entry:

>>> member1 = Member(firstname='raj', lastname='test')


>>> member2 = Member(firstname='rajesh', lastname='test')
>>> member3 = Member(firstname='test', lastname='test')
>>> member4 = Member(firstname='test1', lastname='test')
>>> member5 = Member(firstname='test2', lastname='test')
>>> members_list = [member1, member2, member3, member4, member5]
>>> for x in members_list:
>>> x.save()

Now there are 6 members in the Member table:

>>> Member.objects.all().values()
<QuerySet [{'id': 1, 'firstname': 'raj', 'lastname': 'test'},
{'id': 2, 'firstname': 'raj', 'lastname': 'test'},
{'id': 3, 'firstname': 'rajesh', 'lastname': 'test'},
{'id': 4, 'firstname': 'test', 'lastname': 'test'},
{'id': 5, 'firstname': 'test1', 'lastname': 'test'},
{'id': 6, 'firstname': 'test2', 'lastname': 'test'}]>

Django Update Data


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 = "ankit"


>>> x.save()

Execute this command to see if the Member table got updated:

>>> Member.objects.all().values()

Hopefully, the result will look like this:

>>> Member.objects.all().values()
<QuerySet [{'id': 1, 'firstname': 'raj', 'lastname': 'test'},
{'id': 2, 'firstname': 'raj', 'lastname': 'test'},
{'id': 3, 'firstname': 'rajesh', 'lastname': 'test'},
{'id': 4, 'firstname': 'ankit', 'lastname': 'test'},
{'id': 5, 'firstname': 'test1', 'lastname': 'test'},
{'id': 6, 'firstname': 'test2', 'lastname': 'test'}]>

Django Delete Data


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})

Which tells us how many items were deleted, and from which Model.

If we look at the Member Model, we can see that 'Jane Doe' is removed from
the Model:

Member.objects.all().values()
<QuerySet [{'id': 2, 'firstname': 'raj', 'lastname': 'test'},
{'id': 3, 'firstname': 'rajesh', 'lastname': 'test'},
{'id': 4, 'firstname': 'ankit', 'lastname': 'test'},
{'id': 5, 'firstname': 'test1', 'lastname': 'test'}]>

You might also like