What is Django Python? Build your first program from scratch
Tags: django, python, webdev, framework
Published: 2020-09-18 23:01:12

**Django** is a popular Python open-source web development framework used for rapid web development and clean, pragmatic design. It is a robust and approachable framework that lets you focus on your application by having salient parts pre-baked that are fairly standard practice.  This framework makes it easier to focus on writing apps instead of reinventing the wheel.

Django is used in all sorts of tech stacks, including Instagram, Pinterest, Mozilla, and Eventbrite. Companies everywhere are actively using Django and invested in its development. In 2020, it is the 4th most wanted web framework according to StackOverflow.

Today, we will introduce Django and build a program from scratch. If you want to get started today, knowledge of the following concepts will be helpful. 
* HTML/CSS
* Python
* How HTTP Requests work
* How relational databases and how SQL works


**In this article, we will look at:**
* [What is Django?](#what-is)
* [Django Design Pattern](#pattern)
* [Django vs. Flask](#vs)
* [How does Django Work?](#how)
* [`Hello World` in Django](#hello)
* [Build your first Django program from scratch](#build)
* [What to learn next](#next)

<br>

<br>


> <h3> <b>Take your Python web dev skills to the next level</b>
>
> Learn how to create powerful Django apps. Ideal for intermediate or beginner Python developers. 
>
> <b>[Django: Python Web Development Unleashed](https://www.educative.io/courses/django-python-web-development)

<br>

<a name="what-is"></a>


## What is Django?

Django is a high-level, web framework written in Python for rapid development and pragmatic design. A framework is simply a collection of modules that are grouped together for creating web applications from a reliable, pre-existing existing source. Django offers a large collection of theses modules.

Django was created in 2003 when web developers working for a newspaper company in Lawrence, Kansas, needed a better way to organize their code. Because the developers were surrounded by many newspaper journalists, clear documentation became an integral part of the project that became known as the “Django” project.

Django has since blossomed into a massive online open-source community that has a solution for just about everything you can think of, from authentication to content management systems. 

<br>

### Benefits of Django 

There are several benefits to using Django over other possible solutions:
* **Fast:** because of the way Django is set up, you can get off the ground very quickly. It doesn’t really take any time at all to get a Django application setup if you have the architecture of the app already in mind. 
* **Scalable:** Django can meet the traffic demands of a large project.
* **Fully loaded:** there are all sorts of packages that you can use to carry out standard web application tasks like authentication or content administration or querying. It’s all pre-baked in. 
* **Versatile:** Django is fairly versatile. You can use it for all sorts of applications. The sky is the limit really on what you can do with it. 
* **Secure:** common security risks are averted with Django’s built-in security protocols for cross-site request forgeries, cross-site scripting, clickjacking, and SQL injection.
* **SEO optimized:** Django makes SEO easier by maintaining a website through URLs rather than IP addresses.
* **Documentation:** Django's documentation is one of the best on the market. It's easy to read, even for people with no technical background.

With Django’s versatility, it’s certainly capable of meeting your project’s needs. Companies like Spotify, Pinterest, National Geographic, and Dropbox use Django for their business models. Let’s take a look next at the common design patterns that these companies have used so you can get a feel for the shape of a typical project. 

<br>

<a name="pattern"></a>

## Django Design Pattern 

There are three major components to Django’s architecture: elements that aid in working with the database, a template system that works for people who don’t program, and a framework that automates a lot of the website management. This lends itself to a Model, View, Template design pattern: 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/x142w35gz5r0z0uuz6bg.png)

* **Model:** defines the structure of the database
* **View:** defines the logic that returns something from an HTTP request. 
* **Template:** defines the structure of how a web page will look with plaintext information that can be read by someone who doesn’t necessarily program

These constituent parts are put in their own distinct files named for their purpose in Django web applications. In addition, you might have a URL mapper that deals with routing to a specific view for different endpoints.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/xzw3vth2hf2hznrebbq4.png)

<a name="vs"></a>

## Django vs. Flask

So far we have taken a look at an introduction to Django. So, how does it really differ from another popular Python solution, Flask? 

Flask is a **microframework**, meaning it is simple but extensible. Flask is based on the concept of doing one thing and doing it well. Flask does not need any tools or extra libraries. It also does not possess any database abstraction layer.

Django, on the other hand, is a **batteries included** framework that provides many things out of the box. It offers less control than Flask, with the inclusion of an admin panel, an ORM (Object Relational Mapping). Django has the goal of simplifying website creation.

*So, which is better?* There isn't really a solution that is better or worse. It comes down to your requirements. They are both great in their own market and domains. At a high-level, Django provides the advantage of being a full stack framework. Generally, teams prefer Django over Flask for its variety.

<br>

<a name="how"></a>

## How does Django work?

In Django, we can make projects and applications. In most instances, the terms can be interchangeable, but in Django they are not. Projects can contain several smaller applications that serve a particular function or purpose. In a library project, we can have a registration application, a login application, a catalog application, etc..

The root directory will look something like the code below when we create a run the application’s migrations. *Later, we’ll go over how to actually install and run Django on your device.*

```py
¬project_1/
¬project_1/
	__init__.py
	asgi.py
	settings.py
urls.py
wsgi.py
¬application_1
	¬migrations
		__init__.py
	__init__.py
	admin.py
	apps.py
	models.py
	tests.py
	views.py
	manage.py
```

**The inner `project_1` folder contains all the pertinent files for your project.**

* `__init__.py`: Empty file that signifies it’s a Python package. 
* `asgi.py`: Asynchronous Server Gateway Interface. 
* `settings.py`: contains all of the core information needed for your project to actually work, such as database connection, api keys, static files, and more.
* `urls.py`: Project Level url mapper. Maps to specific views or to another application level url mapper. 
* `wsgi.py`: Web Server Gateway Interface. 

**The `application_1`  folder contains all the pertinent files for your application.**

* `migrations: Migrations from db are stored here
* `__init__.py`: Empty file that signifies this is a Python app
* `admin.py`: register models  here
* `apps.py`: app config 
* `models.py`: create models here
* `tests.py`: create tests here
* `views.py`: create views here

When we run our server, the server configures Django’s default configuration with your add-ons that are setup in `settings.py`. Your `ROOT_URLCONF` points to the URL mapper in your project folder. The URL mapper then points to views, which contain logic to return a response to some sort of HTTP request. 

The `models` file is where we create the schema for our table. We use SQL-like syntax to make constraints on the data that gets passed. We register the models in the admin file so that we can run migrations on the project after registration.

When learning how Django works, it’s easiest from the top down, starting at `settings.py`. From there, you can navigate through the project by going to the project’s URL mapper.

It’s best want to understand how the structure works is by creating a project, so let’s do it! 

<br> 

<br>

<a name="build"></a>

## Build your first Django program from scratch

So, now we understand the basics of `Hello World` in Django. Let's take this a step further and build our first proper Django project from scratch. 

<br>

### Step 1: Django Installation
**Windows**

1. Make sure to have Python 3 installed
2. Create a virtual environment by navigating to the folder you want to create it in and  entering: `py -m venv project-name`
3. Start the virtual environment: `run  project-name\Scripts\activate.bat`
4. Install Django: `py -m pip install Django`
5. Verify installation with `django-admin --version`

<br>

**Mac:**
1. Make sure to have Python 3 installed. Anytime you use python in the command line, you’ll use `python3` instead. 
2. Install pip:
   - Download: `curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py`
   - Run: `python3 get-pip.py`
3. Install virtualenv: `python3 -m pip install virtualenv`
4. Navigate to the place where you would like to create your virtual environment
5. Create virtualenv: `virtualenv <name_of_virtual_env>`
6. Use `cd` to get into `virtualenv`
7. Activate virtualenv: `source bin/activate`
8. Install Django: `python3 -m pip install Django`

<br>

### Step 2: Initialize Project


A `Django` project is a collection of applications and configurations. The following command will create a Django project in the `first_project` directory: `django-admin startproject first_project`

1. In your virtual environment command line, run `django-admin startproject first_project`. This creates the workspace that will encapsulate all of your applications and your config files.
2. `cd` into `first_project`.
3. Run (Mac) `python3 manage.py runserver` or (Windows) `py manage.py runserver` and open up `localhost:8000` to see if you get a site with an animated rocket that tells you your install worked!


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8suwyqxqub0ckigrda3z.png)

> **Note:** You might get an error in your terminal saying you need to run migrations. Don’t worry about that at this point since we are not working with a database. 


<br>

### Step 3: Create Application 
As mentioned in previous sections, projects and applications are very different in Django. An application serves one basic purpose or function. In this sample application, we’ll create a basic `Hello World` application for our `first_project`. 

1. In your virtual environment, run (Mac) `python3 manage.py startapp first_app` or (Windows) `py manage.py startapp first_app`
2. Configure application in project. Look for the `INSTALLED_APPS` variable in the `settings.py` file of the `first_project` folder. After the final application in the list, add the name of our application as a string. 
3. Import the `HttpResponse` package from the HTTP Django module to create a view: `from django.http import HttpResponse`

4. Create a view function: `def index(request): return HttpResponse(“Hello World!”)`

5. Use Project URL Mapper to route to application view. Navigate to `first_project/urls.py`. Import from `first_app import views` at the top of the file. In the `urlpatterns` list, add the following: `path('',views.index,name="index")`		

6. Execute Project: Run (Mac) `python3 manage.py runserver` or (Windows) `py manage.py runserver` and open up port 8000 to see the result of our example!


<a name="next"></a>

## What to learn next
We’ve just scratched the surface of what Django can do. Learning the Django templates is a great next step for mastering intermediate Django. But there is still a lot to learn! 

Continue your journey by learning how to:
* Create models and forms
* Create a REST API
* Serve static files 
* and much more


All of these concepts and more and covered in Educative’s course **[Django: Python Web Development Unleashed](https://www.educative.io/courses/django-python-web-development).** You'll learn beginning and intermediate concepts alongside tons of real-world projects. At the end of the course, you will have created a few Django projects and solved Django challenges that can be used in your portfolio.

*Happy learning!*

<br>

### Continue reading about web dev and Python
* [A Complete Guide to Web Development in Python](https://www.educative.io/blog/web-development-in-python)
* [Dynamic Programming Tutorial: making efficient programs in Python](https://www.educative.io/blog/python-dynamic-programming-tutorial)
* [The Web Developer FAQ](https://www.educative.io/blog/web-developer-faq)