welcome to the ultimate django course
in this course i'm going to teach you
everything you need to know about django
from the very basics to more advanced
concepts
so by the end of this course you'll be
able to use django to build
production-grade back-ends for your web
and mobile apps if you have always
wanted to learn web development with
python you are in the right place
we'll use python and django to build and
deploy the backend for an
e-commerce application if you're looking
for a comprehensive
organized and practical course that
takes you from zero to hero
and prepares you for the job this is the
right django course for you
everything you need to know about django
is in one place in the right order
so you don't need to jump back and forth
between random tutorials
amash hamadani i have taught millions of
people how to advance their software
engineering skills
through my youtube channel and online
school code with mosh.com
if you're new here be sure to subscribe
as i upload new videos
all the time now let's jump in and get
started
let's talk about what you need to know
to take this course for starters
you need to know python you need to know
the basics of python
as well as object-oriented programming
concepts such as classes
inheritance polymorphism and so on you
should also know the basics of
relational databases
so you should be familiar with concepts
such as tables columns
primary and foreign keys relationships
and so on if you need to refresh the
fundamentals i have a couple of beginner
level tutorials on my youtube channel
as well as comprehensive courses on my
website codewithmosh.com i'll put the
links down below in case you're
interested
all right so i'm assuming that you're
the right student for this course now
let's talk about how you should take
this course
first and foremost i want you to watch
this entire course
all the way from the beginning to the
end even if you're familiar with django
because
along the way i will share a lot of tips
and tricks and i don't want you to miss
out on any of them
if you have taken any of my other
courses you know that i'm not gonna
waste your time with
repetitive or useless stuff so make sure
to watch every lesson
now while watching each lesson i want
you to take notes
you can just write down some keywords on
a piece of paper if you don't want to
write a lot of notes
i strongly believe that the act of
writing things down will help you
remember new things that you learn
then after each lesson go through your
notes and repeat the same steps i showed
you in the video
this is exactly how i personally learn
new things also
i've carefully designed tons of
exercises that help you understand and
remember the materials so make sure to
do all these exercises because the more
you practice
the better you'll be at django or coding
in general
welcome back to the ultimate django
course in this section we're going to
talk about the basics of django
first i will give you a quick
introduction to what django is and
why it's so popular then we'll talk
about the fundamental web development
concepts that every web developer must
know
next we'll set up our machine for
development and create
our first django project once that
project is up and running
i will show you two essential techniques
for debugging django applications
this is going to be a short and sweet
introduction to django so
let's jump in and get started
so what is django and why is it so
popular well
django is a free and open source
framework for building web applications
with python
it's not the only web framework for
python but it's the most
popular one because it helps us build a
website in less time
with fewer lines of code that's why a
lot of companies like youtube
instagram spotify and dropbox use django
in their tech stack
now django is what we call a batteries
included framework which means
it comes with a lot of features out of
the box so we don't have to code them
from scratch
for example it gives us an admin
interface for managing our data which is
a huge time
saver it also has an object relational
mapper that abstracts the database
so we can query or persist data without
writing a lot of sql code
it also comes with an authentication
package for identifying users
it also has a package for caching data
and much much more
so since django offers all these amazing
features
we can focus on our application and its
requirements we don't have to reinvent
the wheel
and code all these features from scratch
now once in a while you might come
across
someone like our popular superstar
developer john smith who thinks django
is a piece of crap
because it's old and bloated with so
many features he used it
hated it and then rewrote his entire
project with a new shiny framework that
is faster
well saying a framework is better than
django because it's faster it's kind of
like saying
a ferrari is better than a truck because
it's faster
what if you want to move something
you're not going to use your ferrari for
that right
so a wise software engineer doesn't pick
up a framework
merely based on his performance there
are so many other things you need to
take into account
like the maturity of the framework how
stable it is from one version to another
its learning curve the size of the
community and so on
django has been around for a long time
and it has a huge community
so there are tons of django packages
built by the community that you can
reuse in your applications
also if you get stuck there's always
someone out there to help you
if you want to hire people there are
tons of people to choose from so these
are the benefits of having a huge
community around the framework
now regarding django features yes django
comes with a lot of features
but you don't have to use or even learn
all of them because
all these features are optional so you
can use the features that make sense for
your application
so in my opinion debates about the best
framework in the world are useless
we all like different things and just
because someone doesn't like django it
doesn't mean it's bad
a lot of companies are using django and
are looking for django developers
here in the us the average salary of a
django developer is just over
117 000 a year so
if you like python and want to get into
web development learning django is a
good investment for your future
[Music]
so you learned that django is a
framework for building web applications
with python
now let's talk about some of the
fundamental concepts you need to
understand to build web applications
let's say we're going to build an online
store and publish it at moshby.com
now this website is going to have two
parts or two applications
a front end and a backend the front end
is the part that is loaded
inside a web browser on a client machine
it's the part that the user sees and
interacts with
the backend is the part that runs on a
web server
and is responsible for data processing
validating business rules and so on
now let's imagine that alice wants to
visit our website
so she points her browser to moshby.com
this address is also called a url which
is short for uniform
resource locator it's basically a way to
locate a resource on our internet
a resource can be a web page an image a
video
a pdf and so on so alice types
moshby.com in her browser and presses
enter
at this moment a browser sends a request
to the web server that hosts our website
and says
hey alice wants to see the home page so
the web server should take this request
process it and return a response back to
the client
this data exchange is defined by a
protocol called http
which is short for hypertext transfer
protocol
it defines how clients and servers can
communicate
so this is the big picture as alice
navigates our website
for each page her browser sends an http
request to the server
and receives an http response now as
part of building the backend for this
website
we need to decide how we're going to
respond to clients one option is to
generate the requested page on the
server
and return it to the client we use html
for that html is short for
hypertext markup language it's a simple
language for
representing web pages and their content
every webpage you have seen on internet
is built using html
so one option is to generate the page on
the server and return an html
document to the client the other option
is to return only the data needed on the
requested page
and have the client generate the page so
instead of putting a complete page or
a complete html document in an http
response
we only return the data like the list of
products
now what is the difference well if we
push this responsibility to the client
we can free up the server so it can
serve more clients
our application will be more scalable
that's why over the past few years
this approach has become more trendy and
is now considered the industry best
practice
these days we have tools like react
angular and vue for generating web pages
on the client
these are all client-side tools that are
used by front-end developers
in contrast we have server-side tools
for building back-ends
django falls in this category so you
should not compare django with let's say
react
you may compare django with other
server-side frameworks like asp.net core
which is used by c-sharp developers
express used by javascript developers
and so on
so if we push the responsibility of
generating web pages to the client
the server essentially becomes a gateway
to the data
on the server we can provide endpoints
that the client can talk to
to get or save various pieces of data
for example we can provide one endpoint
to get the list of products and another
endpoint to get the list of orders
someone has placed
now all these endpoints together
represent the interface that clients use
to talk to the server
in technical terms we say the server
provides an api
or an application programming interface
to clients this api is essentially like
the buttons on a remote control
all these buttons together represent the
interface or the api we use to interact
with the tv
okay so in this course our focus will be
on using django
to build an api for our online store
client applications can use this api to
get or save the data
how these clients are built is
irrelevant here we can use react
angular or even plain javascript that
falls under front-end development which
has nothing to do with django
once we build this api if you know
front-end development you can
always build a client app that talks to
this api
alright now that you understand the big
picture we are ready to set up our
development environment
and that's what we will do next
[Music]
all right let's make sure you have the
right setup before we start coding
the first thing i want you to do is
upgrade your python to the latest
version
so head over to python.org downloads and
download the latest version of python
for your operating system
once you do that then open up your
terminal window and run
python version to make sure you have
upgraded your python correctly
now here we see python 2.7 because on
mac we have two different versions of
python running side by side
we have the old python 2 which is now
deprecated
and we also have python 3. so if you're
using a mac
you have to run python3 dash dash
version
but if you're on windows or linux you
have to run python
version okay so here i'm using python
3.9.5 great next we're going to use pip
or pip3 if you're on mac to install
pip n i talked about paypal in my python
course
it's basically a dependency management
tool for installing our application
dependencies
in virtual environments this way our
application dependencies will not clash
with other applications dependencies
okay so
let's go ahead and install this
now in this course just like my other
courses i'm going to use visual studio
code or vs code as my editor it's just
my personal preference
if you have a preference for a different
tool like pycharm that's totally fine
having said that i highly encourage you
to use vs code
because throughout the course i'm going
to show you a lot of shortcuts and
time saving tips that will not apply to
your editor
in case you don't have vs code you can
get it from code.visualstudio.com
now once you run it i want you to go to
the extensions panel over here
and search for python make sure
to install this extension because with
this we get features such as
intelligence debugging code navigation
and so on
all right now that we have installed all
the necessary tools let's create our
first django project
so here in the terminal window i'm going
to go to my desktop
you can go anywhere on your machine it
doesn't really matter now we're going to
create
a directory called store front that is
the name of our project
next we go inside this directory and run
pip and install django so we're going to
install django
using pip app inside a virtual
environment
now let's go ahead
all right well take a look so over here
you can see that p-band has created a
virtual environment for this project
down below you can see the path to this
virtual environment
but if you're on windows you're going to
see something like c drive
backslash whatever now if you're on a
mac and using z shell which is this
fancy
colorful terminal window you can hold
down the command key
and click on this path to go into it
otherwise we can just copy this
and use the cd command to go inside this
directory
now take a look so here's our virtual
environment
in this environment we have this bin
folder that contains a bunch of binaries
for example we have python pip django
admin and so on
so back to the terminal pbn created a
virtual environment and
installed django inside that environment
but in addition to this
ppm also created two files in this
directory
pip file and pay file.log so i'm going
to open this directory using visual
studio code
by running code period if this doesn't
work on your machine
just drag and drop this folder onto vs
code
alright so here's our pip file this is
like package.json for javascript
projects
so in this file we can see that our
project needs
this particular version of python and
under packages you can see
the packages that our application is
dependent upon
so here we have django equals asterisk
that means
any version or the latest version of
django
if we installed a particular version of
django we would see that version here
now back to the terminal window we need
to activate this virtual environment
so we'll use the python interpreter
inside this virtual environment
not the one that is installed globally
on this machine to do that we're going
to run
ppm shell
okay next we're going to use django
admin
to start a new project django admin is a
utility that comes with django
so if you run it we can see all these
commands that we can use
to work with django projects as we go
through the course
you will become familiar with this
command in this lesson we're going to
use
django admin start project
and we're going to call that project
store front
now back to vs code django admin created
this directory for our project
and inside this directory it created
another directory
that is the core of our application in
this directory we have these files which
i'm going to talk about in a second
but before i do so let's get rid of this
redundancy
because we have three storefront
directories
the top one is the one that we created
earlier in the terminal
and then we have these two other
directories one for the project
one for the core of our application so
i'm gonna delete
this project directory now we're back in
the previous step so we don't have a
django project at this stage
now back in terminal let's bring up the
last command
but type it period at the end this tells
django
to use the current directory as the
project directory so django is not going
to create
an additional directory for our project
okay now take a look so we have this
directory
which is the core of our application in
this directory we have
this init file which defines this
directory as a package
we have this settings module where we
define our application settings
we have the urls module where we define
the urls of our application
and these two other modules that are
used for deployment
for now don't worry about them now next
to this directory we have
this file manage.pi this is a wrapper
around django admin so going forward
instead of django admin we're going to
use manage.pi
the reason for this is that manage.pi
takes the settings of this project into
account
let me show you what i mean so now that
we have a project
we want to run a web server so another
command that django admin provides is
run server however if you're on django
admin
run server we get an error saying
requested setting debug but settings are
not configured
because at this point django admin
doesn't know about the
settings of our project so now that we
have a project
instead of django admin we're going to
run python
manage.pi now look we see the same
commands
that django admin provides so here we
can say
python manage.pi run server
now optionally we can supply a port
number
if we don't supply this by default this
will use port 8000 but you might have
another application running on port 8000
in that case you might want to
explicitly set the port number
so let's go ahead with that now we don't
get an error
because manage the pi knows about the
settings of our project
now here we get this warning saying you
have 18
unapplied migrations don't worry about
this yet we'll talk about this soon
so if you look over here you can see
that django has started
a development server at this address so
we can copy this and paste it into
browser
or if you're on a mac and using z shell
you can hold down the command key and
click this all right beautiful
our first django project is running
successfully so let's move on to the
next lesson
[Music]
so far i've been using a separate
terminal window but vs code also has
an integrated terminal window that is
easier to use but to use that we have to
properly configure it to use the python
interpreter
inside our virtual environment let me
show you how to do this
so back to our terminal window first
we're going to stop the web server
by pressing ctrl and c okay
now back in vs code on the top under the
view menu
look we have this command pallet the
shortcut on mac is
shift command and p
now here we're going to search for
python interpreter
so currently vs code is using this
python interpreter that is installed
globally on this machine we don't want
to use this you want to use the one
inside our virtual environment but how
can we find the path to our virtual
environment
very easy so back to the terminal
let's run pip and dash dash vm
all right here's the path so let's copy
this
good now back to vs code we're going to
select
enter interpreter path then we're going
to paste the path
and append slash bin slash
python at the end if you're on windows
instead of a forward slash you have to
use a backslash
okay good now
in this project we have an extra
directory vs code
we have a settings file and here we have
the path
to a python interpreter good with this
we can go to the view menu
now look we have this integrated
terminal the shortcut on mac
is control and backtick
now vs code automatically activates the
virtual environment for this project
so here we can run python manage.pi
run server good so going forward
i'm going to use the integrated terminal
window here it's easier
we can always hide it by pressing ctrl
and backtick
or bring it back we can maximize it move
it around and so on
now one quick tip sometimes when running
this command
you might get a syntax error saying
invalid syntax
this happens every now and then when vs
code fails to
activate the virtual environment for
this project to solve this problem all
you have to do
is open a new terminal window and look
vs code executed this command to
activate
the virtual environment for this project
now we can run
python manage.pi run server
great hey guys bosh here i just wanted
to let you know that this tutorial you
have been watching
is actually the first hour of my
ultimate django course
the complete course is about 10 hours
and goes way beyond this tutorial
so if you're serious about learning
django and are looking for a job as a
back-end
developer i highly encourage you to
enroll in the course the course comes
with tons of exercises and solutions
a full e-commerce project that you will
eventually deploy to the cloud
plus a 30-day money-back guarantee and a
certificate of completion you can add
your resume
in case you're interested i'll put the
link down below and if not that's
totally fine let's move on to the next
lesson
[Music]
all right let's talk about apps so every
django project
is essentially a collection of various
apps each providing
certain functionality just like the apps
on your mobile phone
each app provides a certain
functionality right django projects are
exactly the same so in this project
let's open up the storefront directory
and then look at our settings module
now we can collapse this panel by
pressing command and b on mac
or ctrl and b on windows okay now in
this module we have a bunch of different
settings
in this lesson we're going to look at
the install apps
so every django project by default
includes these apps
the first app is the admin app which
gives us an admin interface for
managing our data then we have the auth
app which is used for
authenticating users then we have
content types app which we'll talk about
later in the course
next we have the sessions app which is
kind of legacy we don't use sessions
anymore
a session is a temporary memory on the
server for managing users data
these days when building apis with
django we don't use the sessions app
so we can come here and delete this app
then we have the messages app
which is used for displaying one-time
notifications to the user
and finally we have the static files app
for serving static files like images
css files and so on so each app provides
a certain piece of functionality okay
now we can also create our own apps here
so let's save this file now let's open
up the terminal window by pressing
control and backtick so here's our
terminal window where we have
our development server running we're
going to open a new terminal window
okay now let's expand this to clear the
window we simply press
ctrl and l now we're going to run python
manage.pi start app and we're going to
call this app
playground okay so
let's close the screen now and open up
the explorer panel
all right look here's our new app which
is represented using a folder with a
special structure
so every django app has the exact same
structure
here we have the migrations folder for
generating database tables we'll talk
about that later in the course we have a
complete section about this topic
we have the admin module where we define
how the admin interface for this app is
going to look like
next we have the apps module where we
configure this app
so the name is misleading i don't know
why django developers decided to call
this module apps
it would be better if it was called
config that's just my two cents
next we have the models module where we
define the model classes for this app
we use model classes to pull out data
from the database and present to the
user
next we have the tests module where we
write our unit tests
and finally we have the views module
which we'll talk about in the next
lesson
again the name is misleading this is not
the view that you think if you come from
a front-end development background
so what we have here is essentially a
request handler it's not a view it
doesn't have
a template or html again we'll talk
about that in the next lesson
so we created a new app now we need to
register this app in the settings module
so every time you create a new app
you need to register it here in the list
of installed apps
we simply add the name of the app which
is called playground
save the changes done in the next lesson
we're going to talk about views
[Music]
alright let's talk about views so
earlier you learned that http
is a request response protocol so every
data exchange
involves a request and a response this
is where we use views in django
so here in the playground folder let's
open up the views module
this is where we define our views or
view functions
a view function is a function that takes
a request
and returns a response so more
accurately
it's a request handler in some
frameworks it's called
an action in django it's called a view
but i don't agree with this name because
from an architectural point of view a
view is often associated with something
that the user sees
that part in django is called a template
and we'll talk about that later in this
section
now that aside let's create our first
view function
so we're going to create a function we
can call it anything we want
i'm going to call it say hello
now this function should take a request
object and return a response
so first on the top from django.http
package
we're going to import the http response
class
now in this function we can do anything
we want in a real-world scenario we can
pull data from a database we can
transform data
we can send emails and so on for now
let's just return
a simple response so we're going to
return
an instance of the http response class
and in this object in this response you
want to add a simple string
so let's say hello world okay
so this is our first view or first view
function
now we need to map this view to a url so
when we get a request at that url
this function will be called and that's
what we're going to do next
[Music]
alright here's our django project now
let's say whenever we send
a request to playground slash hello
our view function should be called and
return hello world to the user
let's see how we can do that so back to
our project
here in the playground folder we're
going to add a new file
called urls.pi you could call it
anything the name doesn't matter
but by convention we call it urls now
in this module we're going to map our
urls to our view functions
so on the top we're going to import the
path function from django.urls
so from django.urls we're going to
import the path function
now don't worry about memorizing any of
these as you practice
all of this will become second nature
also
from the current folder we should import
the views module
so we can reference our view function
now we should define
a special variable called url patterns
all in lower case make sure to split it
properly because this is what django
looks for
we should set this to an array of url
pattern objects
we use the path function to create a url
pattern object
so if we call this function look at the
signature of this function
this function has a bunch of parameters
the first one is route
which is a string the notation you see
here is called type annotation which is
kind of a new feature in python
with type annotation we can see the type
of parameters
and the return value of a function so
the first parameter is route which is a
string
the second parameter is view which is a
function that returns
http response object now look over here
this notation represents the return type
of this function
so the path function returns a url
pattern object
so i'm going to call this function and
give it two arguments a route or a url
which is playground slash hello and
a view function so from the views module
we're going to get
say hello note that i'm not calling this
function so here we don't have a pair of
parentheses
we're just passing a reference to this
function okay
so what we have here is called a url
conf module
that basically means url configuration
so every app
can have its own url configuration but
now we need to import this url
configuration
into the main url configuration for this
project
where is it you saw it earlier so
back to the explorer panel here in the
storefront folder
we have another url's module
up here we have a bunch of comments
about how we should use this module
now look over here if you want to
include another
url conf there are two things we need to
do first we need to import the include
function
from django.urls so over here we have
from django.urls
we're going to import the include
function next we need to add
a url to url patterns
so in this module we also have a url
patterns object which is an array
of url patterns object so here we're
going to call path
give it a route and then we use the
include function
to reference the url configuration
module
in this app so
we're going to call path and say
any urls that start with playground
followed by a forward slash should be
routed to
our playground app so this is where we
use the include function
now the include function requires a
parameter that is a string
here we're going to reference playground
dot urls
so if we send the request to playground
slash hello django knows that
all requests that start with playground
should be handled by this
app so it's going to chop off the first
part of this url
and pass the rest to the url
configuration module
in the playground app so back to this
url's module
we no longer need to add playground here
because we added it once
in the main url configuration module
so we simply add hello followed by a
forward slash i forgot to add that we
always end our routes with a forward
slash
so let's save the changes now whenever
we change our code
django web server automatically restores
itself
so let's open up the terminal window
make sure we don't have any arrows good
so back to the browser let's send a
request to this endpoint
great we see hello world on the screen
so this is how we can map
urls to view functions next we're going
to talk about templates
so i told you that views in django are
not really views they're more like
request handlers or actions
what we often call a view in other
frameworks is called a template in
django
so let's see how we can use a template
to return html content to the client
so here in the playground app we're
going to add
a new folder called templates
and in this folder we're going to add a
new file called
hello.html and of course we could call
it anything
and here we can write some html markup
for example we can type
h1 and press tab to add an h1 heading
and say hello world now don't worry if
you don't know html we're not going to
use it in this course
i just want to show you how django
templates work
so let's save the changes now back to
our view function
instead of returning a plain http
response
we're going to use the render function
to render a template and return
html markup to the client so let's
remove this line
and call the render function now look at
the return type
of this function it returns an http
response object
so here we're going to return the
response
now let's remove the brackets and type
them again so we can see the function
signature
the first parameter here is a request
object and
the type of this is http request
so we're going to pass this request
object
right here now the second parameter
that's the name of our template which is
a string
so here i'm going to say hello.html
the other parameters are optional so
don't worry about them at this point
now save the changes let's make sure our
project works up to this point
so back in the browser refresh beautiful
now we see html content we can verify it
by right clicking on this page and
looking at the page source so look we
are returning
html content great now let's make this a
bit more interesting
so back to our template instead of hello
world
we can dynamically render some value so
back to review function let's type a
comma
to see the next parameter that is a
context object
and the type of this is a mapping of
string
to any that means we can pass any
mapping object
that maps a string value to any other
type of
object so here we can pass a dictionary
so let's pass a dictionary the type of
the key should be a string so we can
call that name
and we're going to set that to a value
like let's say mosh
now back to our template
instead of hello world we can render the
name that we passed here
so we type two pairs of braces and in
between
we type the name of the key save
refresh beautiful now in this template
we can also write some logic so we can
type an if statement so we type braces
and in between them we add two
percentage signs
in between them we can write an if
statement so we can say
if name is set we can render it here
otherwise
we can render hello world
and of course we need an end if clause
as well so
and if now this syntax is kind of ugly
but the good thing about django is that
it's modular so you can easily replace
django's default template engine with
your preferred template engine but once
again we don't really use templates in
django
projects that often these days there are
special cases for them but
for the most part we use django to build
apis that return data
not html content so i just included this
lesson
so you know what templates are and how
they work we're not going to spend any
more time on templates for now
unless we encounter a situation where we
really need them
[Music]
let's talk about debugging django
applications in vs code
this is particularly useful if our
application doesn't produce the right
result and we want to run it line by
line and see
where exactly something has gone wrong
so click on this icon
to open the run and debug panel now the
first time you see this message saying
we should create a launch.json file
basically we need to create a launch
profile
so vs code knows how to run or debug
this application
so let's click on this now in this list
select django all right here's our
launch.json file
what you see here is kind of like a
dictionary in python we have a bunch of
key value pairs
these key value pairs define a launch
profile
so vs code knows that to run this
application
it should use the current python
interpreter
to run manage.pi which exists
in our workspace folder and then as an
argument
it should pass run server to it here we
can add
an additional argument to specify the
port
so it doesn't clash with port 8000 which
is currently in use
okay save the changes we're done with
this file
so let's close it now if you're curious
let me show you where this file exists
it's added to our project up here inside
the vs code folder so here's our launch
profile
now that we have a launch profile if we
go to the run and debug panel
we see something else so here we can
start our application for debugging
but before doing so i want to write some
dummy code here in our view function
so let's set x to 1 and
y to 2. now i'm going to click on this
line
to insert a breakpoint when we add a
breakpoint
via scope will execute every line of
code until
it hits our breakpoint from that point
onward
we can execute our code line by line so
let's add a breakpoint and then start
the application for debugging
all right let me collapse this window
good
so in this new terminal window we have a
development server
listening on port 9000 so let's hold
down the command key on mac or
control on windows and click on this
link
all right here's what we get the home
page of our project is gone
because we have registered a custom
route that is playground
hello so we see the homepage only the
first time we run our django project
so let's go to playground hello
all right our breakpoint is activated
and we are on this line
now on the left side in the variables
section you can see the local variables
so currently we have the request object
that is the request object that
we receive in this function so we can
expand it
and inspect its various attributes
we don't want to do that for now so
let's close this
we want to execute our code line by line
so here we have a bunch of functions
the first one is step over and the
shortcut for this is f10
with this we can step over the current
line so if we press f10
this line gets executed and now we are
on the second line
now look over here in the list of local
variables we have
x and its value is one this is very
useful when debugging applications
so if something is not calculated
properly we can inspect it here
now most of the time you can see your
local variables here
but if not you can always add them in
the watch window
so before recording this video i was
practicing that's why you see x here
let me select this and delete it so in
your watch section you're not going to
have any variables
to add one we simply click on this and
then type
the name of our variable okay so this is
how we can step over
various lines so we can press f10 again
and again
so this function is executed and now
back in the browser
we see the final result now let's do
something more interesting
so back to our code let's close
the terminal window so we have more
space i'm going to define
a function here called calculate
and here we're going to set x to 1 y to
2 and return x
just some dummy code now over here
we're going to call the calculate
function okay
now save the changes back in the browser
let's refresh so our view function gets
caught
now we are right here now this time
instead of stepping over this line
we want to step into it because if you
step over this line
we're not going to see what happened in
the calculate function
we see the final result so we see x is
set to 1 and
we can verify that over here as well but
sometimes we need to step into a
function to see
what is happening there maybe there is a
bug inside the calculate function
so let's restart the debugger
okay i'm going to close this back in the
browser
let's refresh this page
okay we're back to this line now this
time we're going to step into this
function
so look over here this is the icon for
stepping into a function
and as you can see the shortcut is f11
so if you press f11
we go inside the calculate function now
we can execute each line
using f10 or step over and see where
something has gone wrong
now let's imagine this calculate
function is a large function with a lot
of code
at some point we want to step out of it
without having to execute
every line of code in this function
there's a shortcut for this
so look over here that is step
out the shortcut is shift and f11
so if we press shift and f11 we get back
to the previous function so this is how
we can debug django applications in vs
code
now once we're done it's always a good
practice
to remove these breakpoints otherwise
they get in the way
so as you debug your applications you
place various breakpoints in different
parts of your code
and you will hit them all the time so
always remove your breakpoints
once you're done with them so we're done
with this debugging session
now we can disconnect by pressing shift
and f5 or clicking on this icon
all right now one last tip before we
finish this lesson
on the top under the run menu look
we have a command called run without
debugging
the shortcut on mac is control and f5 so
if we use this shortcut we can start our
application
without having to run python manage.pi
run server let me show you what i mean
so
first let's bring up our terminal window
here's the second terminal window that
we use for debugging
i'm going to delete this here's the
first terminal window where
we started our application by running
python manage.pi
run server so let's press ctrl and c
to stop the server good i'm also going
to delete this terminal window
let's imagine we just opened this
project in vs code day one
now to run this application without
debugging we can press
ctrl and f5
now our application has started on port
9000
so we can go to this address and then
hit playground hello
so this is how we can run our
application without debugging
just remember that if you use this
command your breakpoints are not going
to get hit
so if you want to debug your
applications you should start it
in the debug mode
[Music]
there is another way to debug django
applications using a powerful tool
called
django debug toolbar so if you go to
google and
search for django debug toolbar you're
going to find this page
over here you're going to find the
installation instructions
so i highly encourage you to follow
along with me and repeat the same steps
so we installed this toolbar together so
first we have to use pip or ppf to
install
django debug toolbar so back to vs code
i'm going to open up a new terminal
window
and as you can see vs code used the
source command to activate our virtual
environment
so now let's run pipen install
django dash debug dash toolbar
good now back to the documentation
the next step is to add debug toolbar in
the list of installed apps
in our settings module so back to vs
code
we can press command and p on mac or
control and p on windows
to bring up the search box now we search
for our settings module
good now in the list of install apps at
the end
we're going to add debug underline
toolbar
good now the next step
the next step is to add a new url
pattern in our main url conf module
so i'm going to copy this line and back
to vs code let's bring up the urls
module
we're going to pick the one in the
storefront folder
okay now we add a comma here and paste
that line
now here we have a compilation error
because debug toolbar is a module that
we have to import on the top
so if you look at the documentation you
can see that over here
import debug toolbar so copy this and
paste it right here
good now back to the documentation
the next step is to add a middleware we
use middleware to hook into django's
request response processing
so in our settings module we have a
setting for middleware
we're going to add this line in that
file so copy this
back to the settings module here we have
the install apps
right after that you can see the
middleware setting
so we're going to add that on the top
now the final step is to add our ip
address
in the internal ips setting so for local
development
we should use 127.001
so i'm going to copy this entire setting
because by default
this doesn't exist in a new django
project so copy this
and i'm going to paste it anywhere in
this settings file it doesn't really
matter
okay save so we have completed all the
steps
now back in the browser if you go to
this url playground
slash hello we don't see the toolbar it
should appear here
because the toolbar only appears when we
return a proper html document
if you right click here and look at the
page source
you can see that we are not returning a
proper html document
so we don't have the html head and body
elements
so let's open up hello.html now on the
top we type
html press tab now inside these elements
we're going to add
a body and then inside the body
we're going to add the code that we had
earlier so let's move that right here
good now we have a proper html document
of course the head element is missing
but it doesn't really matter
now back to the browser refresh and
here's django debug toolbar
here we have different panels like
history for seeing the urls we have hit
so far
we have versions to see the version of
django python and
debug toolbar we're running we have
processing time
we have our settings we have request
headers and so on
now my personal favorite panel is the
sql or
sql panel here we can see the queries
that are sent to the database so later
in the course
where we talk about querying the
database using django's
object relational mapper we're going to
come back to this panel and see
what queries django will generate and
send to the database
so that's it for this lesson we're done
with this section in the next section
we're going to talk about
building a data model so i'll see you in
the next section
welcome back to another section of the
ultimate django course
in this section we're going to talk
about models which are used to store and
retrieve data
we'll start off by quick introduction to
data modeling to make sure you know the
essential concepts
then we're going to design the data
model for an e-commerce application
next we're going to talk about
organizing our models in apps to improve
reusability
this is one of the areas that is often
misunderstood so i'm going to demystify
it once for all
and then we'll spend the rest of this
section in coding model classes
we'll use these classes to store and
retrieve data throughout the course
so let's jump in and get started
[Music]
the first step in every django project
is figuring out the pieces of data we
want to store
so what entities or concepts do we have
in an e-commerce application
well for starters we need the concept of
a product with attributes like title
description price and inventory now in a
real scenario
a product entity might have other
attributes it really depends on the
requirements of our application
for now we just want to keep things
simple okay now quite often
our products are divided in different
categories like shoes
beauty products fruits and so on so we
need another entity called collection or
category with an attribute called title
now we need to add a relationship or an
association between these entities
so we can start from one end and
navigate to the other end
for example we can get a collection and
find all the products in that collection
okay now let's assume that in our
application
a product can belong to one and only one
collection
and a collection can have multiple
products
so an asterisk represents many we could
also use an
n here okay now we have a one-to-many
relationship
between collection and product so
relationships can be one-to-one
one-to-many and many too many back to
our diagram
now over here we can add a label called
products and that means
when we code these entities or these
classes in the collection class we're
going to have an
attribute called products for now i just
want to hide this for simplicity okay
now sometimes we can have multiple
relationships or
multiple associations between two
entities so let's imagine that a
collection
can optionally have a featured product
that is the product
whose picture we want to show to the
user so we can add a second relationship
between
these entities now look at this number
here zero to one means
a collection can have zero to one
product
and we're gonna call that attribute
featured product so once again
that means in the collection class we're
going to have an attribute
called featured product okay now you
might ask
what about the id attribute shouldn't
every entity have an id
attribute yes but django is going to
automatically create that for us
that's why i haven't shown it here now a
little exercise
for you grab a piece of paper and
identify the
other essential entities we need in an
e-commerce application
just the bare minimum don't go ahead and
create a complex diagram like this
i don't want this there are only five
entities that i want you to identify
so spend a couple minutes and identify
these entities along with the attributes
and
relationships then come back see my
solution
all right so this is what we ended up
with in the previous lesson we have a
one-to-many relationship
between collections and products now
don't take this as a hard and fast rule
maybe in your application a product can
belong to many collections
then you're gonna have a many-to-many
relationship between products and
collections okay
so back to our model i'm gonna remove
the collection from here
so we have some free space on the screen
now what else do we need here
well in every e-commerce application we
have the concept of a shopping cart
right so we're going to have an entity
or a model or a class called
cart with an attribute called created at
let's assume that we need to know when
each card is created
so every now and then we can do a clean
up and remove cards that are 30 days old
i just made this up but in a real
scenario you should always design your
models
based on the requirements of your
project don't make up your own rules
okay
now we need a relationship or an
association between products and cards
because a card can have multiple
products and a product might be in
different cards
so here we have a many-to-many
relationship between product
and cart now sometimes the relationship
between two entities can have
attributes for example if a product is
in a shopping cart
we need to know how many instances of
that product we have in the shopping
cart
so this relationship itself should have
an attribute called
quantity so we're going to add a new
entity here called
cart item now look at the notation i've
used to represent this concept
i've connected cart item to the
relationship using a dashed line
that means cart item represents the
relationship between these two entities
product and cart this is what we call an
association class
so cart item is an association class
okay
now there's another way to show this
instead of using an association class we
can add a relationship between
cart and cart item because a cart might
contain
multiple items and an item belongs to
one and only one cart
similarly we can add a relationship
between product and card item because
each card item represents
a single product and a product might be
referenced by
many card items so here we have two
one too many relationships between these
entities
now compare this with the association
class notation
so we can either add a many-to-many
relationship with an association class
or two one-to-many relationships it's a
matter of personal preference okay
so we're done with the shopping cart but
you might ask what about the user or the
customer that owns this cart
where is that in the diagram well i
haven't connected cart with an entity
like
customer because we don't want to force
people to register and log in
before they can add products to their
shopping cart okay so there is no
relationship between cards and customers
so cars are essentially anonymous anyone
can have a cart
whether they're anonymous users or
registered customers okay
so we're done with the cart now let's
talk about customers
so our customer entity can have
attributes like name
email username password and so on now
for simplicity
i'm only showing name and email here now
a customer can have
many orders and each order belongs to
one and
only one customer so we need a
one-to-many relationship between
customers and orders
now once again the order entity might
have multiple attributes
for now we just want to know when this
order was placed okay
now an order can contain multiple
products and a product can be in
multiple orders
so we have a many-to-many relationship
between orders and products
and similar to the shopping cart example
this relationship itself needs
attributes
so here we need another entity called
order item with an attribute called
quantity that's our association class
alternatively
you could add a relationship between
order and order item
because each order may contain multiple
items and each order item
belongs to one and only one order
similarly an order item references one
and only one product
while a given product might be
referenced by multiple
order items so two one-to-many
relationships
so these are the entities that i wanted
you to identify but to make this project
more interesting
i decided to throw in one more entity
tag
here we have a minute-to-many
relationship between products and tags
because the product can have many tags
and the tag might be referenced by
different products we'll come back to
this entity in the next lesson
[Music]
so i told you that a django project
contains one or more apps
and just like the apps on your phone
each app in a django project provides
a specific piece of functionality so
that means
each app is going to have its own data
model so in this lesson we're going to
look at a few different ways to
organize our entities in different apps
one way is to have a single app called
the store
and drop all of our entities here now we
can bundle and distribute this app via
pip
and this way anyone can install this app
in their project
and get all these models and the
functionality around them
so next time we're working on an
ecommerce project we don't have to
rewrite the same functionality
over and over we simply install this app
in our project
and write extra code for customization
great
but there's a problem here as this
application grows and
gets more complex it gets bloated with
too many things
like too many models too many views and
other stuff
this is what we call a monolith like a
large heavy piece of stone
so at some point our application might
become hard to understand
hard to maintain and hard to reuse it
becomes like one of those remote
controls with too many buttons
when designing these apps we want to
follow the unix philosophy
so each app should do one thing and do
it well
so here's another solution we can break
down this project into four small apps
the products app which represents a
product catalog
so here we're gonna have three entities
product collection
and tag then we're going to have the
customers app for
managing customers we're going to have
the shopping cart app
for adding the shopping cart
functionality and the orders app
for adding the ordering functionality
not bad right
well this is actually a poor way of
breaking down this project for a number
of reasons
look at the coupling or dependency
between these apps
the orders app is dependent on the
shopping cart app which is dependent on
the products app
so next time we're working on an
e-commerce project we'll have to install
all these apps one by one first we have
to install the products app
followed by the shopping cart app the
customers app and the orders app
ideally each app should be
self-contained so we can easily drop it
into a new project the other problem is
that if we publish a new version of the
products app
that might cause a breaking change in
the shopping cart and
subsequently orders apps so anyone using
these apps have to upgrade
all these apps together again more and
more work
also it doesn't really make sense to
have the shopping cart functionality
without having a product catalog right
why would we ever want to add the
shopping cart functionality to a project
without a product catalog so shopping
cart functionality and product catalog
always go together by the same token
why would we ever want to add the
shopping cart functionality to a project
without the ability to place an order
just to allow people to add something to
their shopping cart
then what again it doesn't really make
sense so these concepts are highly
related and should be bundled together
if we separate them we increase coupling
between apps and we end up with the
problems i just talked about
so does it mean we have to go back to
the monolithic design no
there is a middle ground here look at
the tag entity
the ability to tag products is optional
we don't necessarily need it in every
e-commerce application
in fact we might need it in other types
of applications like your blog
or video platform and so on so tagging
is not specific to products or an
e-commerce application
it's a separate piece of functionality
so i'm going to move the tag entity to a
separate app called
tags and here we're going to have
another entity called
tagged item which represents an item
that is tagged
it can be a product an article a video
and so on it's an
abstract concept now with this
separation
each app is self-contained and provides
a specific piece of functionality
so we can use either or both of them in
a new project
depending on what we're going to build
plus we have zero coupling between these
apps
so we can independently change and
deploy them without affecting other apps
this is the proper way to break down
this project into multiple apps
so here's the takeaway if our app
boundary is so large
we'll end up with a monolith that gets
bloated and becomes hard to reuse
on the other hand if our app boundaries
are so small and fine grained
we'll end up with a lot of coupling
between them a good design is one with
minimal coupling
and high cohesion meaning high focus so
each app is focused on a specific piece
of functionality and
includes everything needed to fulfill
that piece of functionality
okay so back to vs code we're going to
create two new apps
so we run python manage.pi
start app the first app is store
and the second one is tags
okay now as i told you before every time
we create a new app
we should add it in the list of
installed apps so
let's close this window and go to our
settings module
here's the list of install apps i'm
going to add those apps
right here so store and tags
all right we're done with this step
starting from the next lesson we're
going to create the model classes for
these apps
hey guys bosh here i just wanted to let
you know that this tutorial you have
been watching is
actually the first hour of my ultimate
django course
the complete course is about 10 hours
and goes way beyond this tutorial
so if you're serious about learning
django and are looking for a job as a
back-end developer i highly encourage
you to enroll in the course
the course comes with tons of exercises
and solutions
a full e-commerce project that you will
eventually deploy to the cloud
plus a 30-day money-back guarantee and a
certificate of completion you can add
your resume
in case you're interested i'll put the
link down below so thank you for
watching and i hope to see you in the
course
you