<!-- {% raw %} -->
<img src="https://i.imgur.com/RWixB90.png">
# Intro to Django
## Learning Objectives
| Students Will Be Able To: |
|---|
| Describe the use case of Django |
| Contrast MVC with Django's MVT architecture |
| Describe the components of a Django project |
| Describe Django's routing methodology |
| Install Django and psycopg2 |
| Build Django's official tutorial app |
## Road Map
1. What is Django?
2. Django's MVT Architecture
3. Components of a Django Project
4. Django's Routing Methodology
5. Installation & Set Up
6. Django Tutorial Setup
7. Code the Django Official Tutorial App
8. Initial Project and Database Setup
9. Complete Through Part 4 of the Tutorial
## 1. What is Django?
Django is one of the most popular Python-based web frameworks and its popularity continues to grow, thanks to the amazing growth of Python itself.
Django was publicly released in 2005 and got its name from one of its creators, Adrian Holovaty, who named Django after his favorite guitarist: [Django Reinhardt](https://en.wikipedia.org/wiki/Django_Reinhardt).
It's designed for the rapid development of highly-secure web applications.
Compared to the minimalist web framework of Express, Django is a much higher-level framework that provides lots of functionality baked-in, including:
- A powerful Object-Relational-Mapper (ORM) for working with relational databases using Python code instead of SQL.
- A built-in admin app for browsing and manipulating data in the database.
- Built-in user management and authentication.
## 2. Django's MVT Architecture
Django's architecture is similar, but different than that of MVC:
<img src="https://i.imgur.com/rA4BtNv.png">
This chart compares MVC to Django's MVT:
| Concern | MVC | Django<br>MVT |
|---|:-:|:-:|
| Database access | Model | Model |
| Code mapped to routes | Controller | View |
| Rendering of dynamic HTML | View | Template |
When developing with Django, we'll just have to be careful to say:
- **view** - instead of **controller**
- **template** - instead of **view**
The fundamental difference between MVT and MVC - other than nomenclature - is that:
In Django many of the responsibilities a controller would normally perform are picked up in some way by the framework itself.
You may also realize that the **View** in MVT appears to be very similar to a controller in MVC, so why not just call views *controllers*? The reasons for this can be found in the philosophy of the Django development team, who have instituted a slight variation of the MVC model because their framework is unique compared to other MVC frameworks - with a heavy emphasis on *convention* and *ease of use*.
- If you'd like to read more on this topic, checkout this clarification provided by the Django team here: [Why did they call it MVT if it's basically MVC?](https://docs.djangoproject.com/en/dev/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names).
MVC and MVT are all related to the MV* family of design patterns. These patterns emphasize separating presentation concerns(UI), application processing concerns, and data management concerns. They also have a wide variety of acronyms and are usually only differentiated by small details and marginal philosophical differences between framework developers. Some common MV* patterns are MVC(model, view, controller), MVVM(model, view, view model), MPV(model, view, presenter) and many others. MVT is just another one of the many patterns modeled after MV*.
## 3. Components of a Django Project
This diagram visually outlines the relationships between the different components of a Django project:
<img src="https://i.imgur.com/1fFg7lz.png">
The quirky thing about Django is how it names its high-level components.
What we think of as a web **application**, Django calls a **project**.
Furthermore, what we think of as part of an app's functionality (or **modules**), Django refers to as **apps**.
A Django _project_ can have many _apps_, and a Django _app_ can belong to multiple _projects_. More on this later.
## 4. Django's Routing Methodology
Because routing is so fundamental to developing web apps, it's worthwhile to know (in advance) an important difference between Express and Django's routing methodology.
Web frameworks such as Express and Ruby on Rails, use both the *HTTP verb & URL* to define routes used to map requests to controller actions.
Other frameworks, such as Django and ASP.NET Core, use *just the URL* when defining a route, ignoring the HTTP verb.
That's why the Python modules used to define routes in Django are named **urls.py** (see diagram above).
## 5. Installation & Set Up
### Using a Virtual Environment
Create a virtual environment:
```
python3 -m venv venv
```
We'll use the built in venv command and call our virtual environment "venv". We can provide any name here, but it makes sense to keep it short and relevant since it will show in our terminal.
*there are other packages like anaconda which can create a virtual environment for you*
ACTIVATE VIRTUAL ENVIRONMENT!
```
source venv/bin/activate
```
**You need to activate the env before you do any work on this project! Every time!**
You can tell when you're in the activated environment because your terminal should show `(venv)` in the command line prompt.
To **deactivate** your virtual environment:
```
deactivate
```
**NOTE:** the lessons in TI will not have you use a virtual environment - however since it's a common practice we'll be using virtual enviroments and installing packages as needed per environment, instead of globally installing packages.
#### Installing packages
Let's install some packages we'll need:
```
pip3 install django
```
"pip3" is the package manager we'll use for python, like "npm" was the package manager for our javascript projects.
Check Django was installed:
```
pip3 list
```
which will return a list of packages currently installed in the environment.
Install "psycopg2" or "psycopg2-binary" which will allow us to use PostgreSQL with Django:
```
pip3 install psycopg2
```
OR
```
pip3 install psycopg2-binary
```
**If you run into an error installing psycopg2, install using this command:**
```
env LDFLAGS="-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib" pip3 install psycopg2
```
***Ubuntu users having issues:***
```
sudo apt-get install libpq-dev
pip3 install wheel
pip3 install psycopg2-binary
```
Now we'll save the installed packages as a list of dependencies in a text file:
```
pip3 freeze > requirements.txt
```
That command should create a new .txt file and it's contents should look like the result from "pip3 list".
<hr>
***IF YOU'RE CLONING A DJANGO PROJECT:***
After creating and entering your virtual environment, install the dependencies from the cloned project with:
```
pip3 install -r requirements.txt
```
<hr>
## 6. Django Tutorial Setup
### Create a Database for the Project
MongoDB automatically creates a database when you use it for the first time.
However, we're not so lucky with SQL databases where we will need to manually create a database that we want to use for a Django project in advance.
Let's create one using the command installed with PostgreSQL:
```
createdb polls
```
Alternatively, we could go into psql `psql <database_name>` and then create the database as follows:
```sql
CREATE DATABASE polls;
```
Run the `\l` command to confirm that `polls` is in the list of databases.
Depending upon how PostgreSQL was installed, you might need the database's username/password. Just in case, make note of the username to the right of the database name in the list.
With the database created, type `\q` to exit the psql shell.
#### Move into your `~/code` folder
The last thing to do is to move into your code folder:
```
cd ~/code
```
Excited?? Ready to build your first Django app? Let's do this!
## 7. Code the Django Official Tutorial App
Django, in so many words, is a beast! Its documentation is hundreds of times larger than that of Express.
A great way to get started learning it is by following the official Django tutorial. It's an excellent tutorial and we'll be getting a lot of information straight from *the horse's mouth*!
Rest assured that we'll be diving deeper into the Django topics touched upon during the tutorial, and more, like learning how to upload images to Amazon S3!
Let's get started by clicking [here](https://docs.djangoproject.com/en/4.1/intro/tutorial01/)!
## 8. Initial Project and Database Setup
To help get you started, we'll cover the following sections together:
- [Creating a project (in part 1)](https://docs.djangoproject.com/en/4.1/intro/tutorial01/#creating-a-project)
- [The development server (in part 1)](https://docs.djangoproject.com/en/4.1/intro/tutorial01/#the-development-server)
- [Creating the Polls app (in part 1)](https://docs.djangoproject.com/en/4.1/intro/tutorial01/#creating-the-polls-app)
- **SKIP** [Write your first view](https://docs.djangoproject.com/en/4.1/intro/tutorial01/#write-your-first-view) - *you will be completing this section.*
- [Database setup section of part 2](https://docs.djangoproject.com/en/4.1/intro/tutorial02/#database-setup)
## 9. Complete Through Part 4 of the Tutorial
You'll continue to work on the tutorial, please complete it through Part 4.
❗ Make sure to complete the [Write your first view](https://docs.djangoproject.com/en/4.1/intro/tutorial01/#write-your-first-view) section that we skipped!
**Don't** complete any parts of the tutorial **after** Part 4.
[Link to Final Tutorial Code](https://git.generalassemb.ly/sei-blended-learning/django-tutorial-final-code)
## References
[Django Homepage](https://www.djangoproject.com/)
<!-- {% endraw %} -->
[Create Admin User](https://docs.djangoproject.com/en/4.1/intro/tutorial02/#creating-an-admin-user)