A Quick Glance of Django
For me, learning Django was very overwhelming at first — I dove straight into the official documentation and its tutorial, making it very frustrating as I got lost every step of the way, getting bombarded with a ton of new terms and acronyms and specific guides giving me different ways to install Django. My goal with this post is to provide a very basic understanding of Django and its overall structure, hopefully easing the learning process a bit by allowing beginners to have a general idea of what’s happening before they dive into the details.
Here are the main ideas I’m going to go through in this post:
- What is a Web Framework?
- Django Architecture
- Django Apps and Core Files
- Example
What is a web framework?
Whenever you type in a URL, your browser makes a request to a server, which will send files — generally HTML — and your browser will process it and display it. At the end of the day, no matter how complicated your web application is, all it does is send files due to a request.
A web framework provides a toolkit of reusable components allowing developers to focus on building their app rapidly without reinventing the wheel. Problems like how do you map a certain URL to a set of code or how do you dynamically create a page according to some data from your database arise in every web app. A web framework will allow you to do that quickly so you can focus on writing the code for the given URL or on the contents of a certain page. These two main problems are called routing and templating, respectively, and are main components in many web frameworks.
Note: Front-end web frameworks are entirely different
Django is one of the most popular and huge open-source web frameworks. It is written in python and companies like Instagram, Doordash, and Disqus use it in their systems, which hopefully is enough to show that Django is robust and scalable.
Django Architecture
Django follows a Model-View-Controller(MVC) architecture, which is split up into three different parts:
- The Model is the logical data structure behind the entire application and is represented by a database(generally relational databases such as MySql, Postgres).
- The View is the user interface — what you see in your browser when you visit a website. These are represented by HTML/CSS/Javascript files.
- The Controller is the middleman that connects the view and model together, meaning that it is the one passing data from the model to the view.
With MVC, your application will revolve around the model—either displaying it or manipulating it.
So say a user will enter a URL in their browser, that request will go through the internet protocols, to your server, which will call Django. Django will then process the given URL path, and if it matches an URL path you have explicitly stated, it will call the Controller, which will then perform a certain action, such as get an entry from your Model(database) and then render a View(ie: JSON text, HTML/CSS/JavaScript Web page).
Django Apps and Core Files
Any Django project will have at least one Django app. Yes, I know, it’s a little confusing. A Django project encompasses the application and all its components, while a Django app is a sub-container of the application with its own functionality that, in theory, may be reusable in another application without much modification. For simplicity’s sake, we will create one app called myapp
under a Django project called MySite
.
A typical Django project structure will look like this:
MySite/
manage.py
MySite/
__init__.py
settings.py
urls.py
wsgi.py
myapp/
views.py
models.py
__init__.py
admin.py
tests.py
urls.py
static/
myapp/
style.css
index.js
background.jpg
templates/
index.html
aboutus.html
post.html
migrations/
__init__.py
0001_initial.py
All the files under myapp/ describe the Django app named myapp.
myapp/models.py
is the Model, or where you define your database. Take a blogging website for example. At its very minimum, you would have a table of blog posts and a table of comments. Each blog post has a title, author, date, and its contents, while comments have the same thing too.myapp/views.py
is the Controller. Um, but why is the controller called views? Here’s a quick answer in the official documentation if you’d like to know. Insideviews.py
you will define different functions/classes( Django offers support for both but most people still use functions) A function defines what happens when a certain URL is accessed and an HTTP request is made the server. Common actions would be to query the database for records and render a certain HTML template file.- Everything under
myapp/templates/myapp/
are templates or HTML files that define your View. When a function inviews.py
renders an HTML file, it can pass objects such as a list of comments in which you can use special syntax to display those comments. Within each template, you can get static files like CSS, Javascript files, or images to give the webpage life. urls.py
is the URL configuration file. This is the file that allows you to map a certain URL to a certain function inviews.py
. Let’s say you have a server receiving requests from the domainmydomain.com
. If you go tomydomain.com/about-us
, a certain function such asaboutus()
will generate a response. Django will also allow you include important information in the URL. An example would be if you wanted to get a blog post with an id of 4. You make Django send the number "4" to a function namedblogpost(blog_id)
when you go tomydomain.com/blogs/4/
and
Example
To give you a little bit more understanding, I have provided tiny snippets of code of different files. The bold are file names that the code below it belongs to.
#myapp/urls.py
from .myapp import viewsurlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^about-us/$', views.aboutus name="about us"),
url(r'^post/(?P<pk>[0-9]+)/$', views.post, name="post"),
]#myapp/views.py
from django.shortcuts import get_object_or_404, renderdef aboutus(request):
return render(request, 'myapp/aboutus.html')def post(request,pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'myapp/post.html', {
'post': post,
})#myapp/models.py
class Post(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
content = models.TextField()
author_name = models.CharField(max_length=100)
date_written = models.DateField(auto_now=True)#myapp/templates/myapp/post.html
<!DOCTYPE HTML>
<html>
<body>
<h1>{{post.title}}</h1>
<div>
<p>{{post.content}}</p>
</div>
</body>
</html>
The class Post
in models.py
describes a table in the database. This is your Model. Each Post
entry has a title, description, content, author_name, data_written.
- If a user goes to
mydomain.com/about-us
, Django will look inurls.py
for/about-us
— which in this case, is the first line. The functionaboutus
inmyapp/views.py
will be called, which will renderaboutus.html
. - If a user goes to
mydomain.com/post/4/
, Django will callpost
inmyapp/views.py
but also pass4
as the variablepk
into the same function.(?P<pk>[0–9]+)
is a regular expression that looks for the number — in this case, “4”.post()
will then search(query) for aPost
object(includes the title, description, etc.) with an id of 4 in our database and send it to templatepost.html
and render it. If it can’t query an entry with an id 4, it will return a 404 error.
Note that there is a url.py
under myapp/
and MySite/
. MySite/url.py
is the root URL configuration file that Django looks at first. So myapp/url.py
must be linked in MySite/urls.py
to be used. For example, I can make anything with mydomain.com/myapp/
in the beginning look up URLs at myapp/urls.py
, where Django will try to match the rest of the URL.
Start Learning!
So yeah, I think that’s about it for this post. Everything here just barely skims the surface, but hopefully with this, you are able to understand the very basics of how Django works. Here are some tutorials I’d recommend that dive deep into Django implementation step by step:
- The Official Django Tutorial
- Django Girls Tutorial
- Modern Django Series by Dylan Stein — provides an extensive walkthrough of Django explaining every tool you use.
Thanks for reading!
If you enjoyed reading it, please leave a clap/comment! I’m pretty new at this and I’d like to get better — any response is welcome :)