What is Django?
“ The web framework for perfectionists with deadlines.”
Django is a high-level Python web framework that promotes rapid development. Django does this by automating many features so the user can focus on coding their app without worrying about aspects like security, views and much more.
Why use Django? Why not Flask?
I personally do not have much experience with Flask but from what I’ve read it seems that Flask is easier to understand when getting started. Django takes longer to set up and requires more background knowledge of programming to take full advantage of their MVT, Model View Template, software design pattern. However, learning to use Django will only benefit you in the future. If you’re looking to be a Python web developer, Django is practically a must. Haven’t convinced you yet? Well some of these popular websites like:
are ALL built in Django. This framework is extremely powerful and in high demand as a skill.
Creating your first Django Project
Let’s learn how to create our own Django project, and we’ll make a small to do app. When starting a new Django project we need to create a virtual environment in Python and install django through there. At first this was very confusing to me, why do I need to create another instance of Python and it’s files somewhere else? However, the reason we do that is just in case we have another project that uses different dependency versions. Our virtual environment will ensure that we have everything we need for that specific project in one place and it won’t affect other projects. To create a virtual environment on windows, first open a command prompt in your project directory (create one somewhere if you haven’t) and enter the following command:
You’ll enter a “virtual_environment_name” you see fit. This will create a directory called “virtual_environment_name” which contains Python standard libraries. For this Django project I’ll actually name my virtual environment projects.To active this virtual environment you’ll enter this into the command line:
This will add a small change to your command line where you’ll see the name of your virtual environment in the beginning:
This is normal and it means you’ve successfully activated your virtual environment! Next you’ll want to install Django using pip:
pip install django
Now that we have Django installed let’s start our Django project. To create a Django project you type this command into the command line while in your virtual environment:
django-admin startproject "project_name"
This should create another directory within your project folder called “project_name”. For this series I’ll call my project name todo_project. This should be the directory that is created:
Let’s double check that everything worked properly and to do this we’ll run the Django development server. Change directory into your django project and enter this command in the command line:
python manage.py runserver
If successful it should display this in the command prompt:
Watching for file changes with StatReloader
Performing system checks...System check identified no issues (0 silenced).You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
October 03, 2019 - 22:20:55
Django version 2.2.6, using settings 'todo_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
The server is located at localhost:8000 and you just need to type that into any web browser , I’ll be using chrome, and you should see this gif.
Congrats! You’ve successfully downloaded Django, ran the development server and we’re ready to start creating our app. Every time you start this project you’ll need to enter the
python manage.py runserver into the command line to view the apps.
Now before we move onto creating our app we should clarify the difference between a Django Project and Django App because I’ll be using both of those terms in this series.
Django Project (todo_project) — This relates to the entire application and it’s parts. Currently it’s the directory we JUST created called todo_project. The amazing thing about Django is that this project can contain multiple apps. You can create a blog, landing page, shopping cart and they’ll all be treated as apps in one django project. You just need to tell django where to point to these different apps.
Django App — This refers to a sub-module of the project. An app is a web app that does something.
A Django project can contain multiple apps. An app can be in multiple projects. If I didn’t explain it well check out the Django documentation where they explain it MUCH better. We’ll refer to the django project as todo_project and any app as “name”_app for simplicity.
Creating our Django App
Now that we have our development server up and running, we need to create our apps that will essentially be our to do list. In your command prompt change directory to your django project and enter this command:
python manage.py startapp "app_name"
Our “app_name” will be todo_app so it will be easy to follow along between the django project and django app. This command will create a directory which will be laid out like this:
These are all the files that will allow our app to work. Now there’s just one small issue, our django project doesn’t know our app exists yet! We need to tell our django project, “Hey we have this app here I want to add”, then tell our project how to point to our app. To add our app we have to go to a file called urls.py in our django project directory. In this case our django project is todo_project so the directory would be:
Once you find it open the file and you’ll want to do three things:
- import the include module, from django.urls import include,path to our urls.py file
- add the app to urlpatterns
- open settings.py in the same directory and add our app to INSTALLED_APPS
This will tell our project where the app is. Anytime you need to add a new app in your django project you’ll want to make sure to add it to the urlpatterns list! The final urls.py file should look:
from django.contrib import adminfrom django.urls import path,includeurlpatterns = [path('todo_app',include('todo_app.urls')),path('admin/', admin.site.urls),]
Then go into the settings.py file and add your app to INSTALLED_APPS:
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','todo_app',]
The path() function and adding it to INSTALLED_APPS is telling our project:
“Hey we have this app called todo_app, and I to add this to our project and I want you to include all the URLs associated with this app in the project.”
Creating our first view and template
To add our first view we need to create a urls.py file in our django app, todo_app. Change directory into your app, in our case todo_app, and you should see the following files:
Create the file urls.py here and add the following code:
from django.contrib import adminfrom django.urls import pathfrom . import viewsurlpatterns = [path('',views.index,name='index'),]
The code looks very similar to the urls.py file found in the project, the only difference in the path function arguments, and we import views.py from our app. The urlpatterns here tells our app what view to load based on the URL. The URL is the first argument in the path function. Generally the home, or index, is just a domain name so it’s not followed by any characters, hence the empty string.
Great, now that we have a URL we need to create a view that tells django what to load when someone goes to that URL. Open up the views.py file found in your django app and let’s create a function called index that’ll load some template when views.index is called:
from django.shortcuts import render
def index(request): return render(request,'todo_app/index.html')
Each view function takes a request argument because a request is being made to that view. Then we’ll have that index function render the index.html template.
This functionality is why django is so popular. There is a specific place that django goes to look for something called ‘static files’ which are files like CSS, JS, images, HTML templates. We need to create this directory first and you do that in your django app folder. Create a folder called ‘templates’, and inside that folder create another folder called ‘todo_app’ (or your app name), and you’ll store your static files in this folder. Create a HTML file and essentially it should look like:
*other static files*
Let’s get our development server running again and see what this looks like. Remember to start your virtual environment and run the server with the code
python manage.py runserver in the project directory. Then go to localhost:8000/todo_app and now when you load the page you should see the contents of your index.html!
Next: Creating Models and Templates
We’ve successfully created our todo app and loaded our first view. Next we have to create our models which are the fields that are stored in our database. Then we’ll see how powerful templates are in django because we don’t need one long HTML file anymore, we can create a base template and have other templates inherit content from it. This will allow us to start working on our todo app and create some functionality.
I know moving between the django project folder and django app folder can be slightly confusing, but as you do this more this switch will be second nature.