Your First Backend Web Server with Django
Tags: django, webdev, python, tutorial
Published: 2024-01-26 17:05:25

Yes!! 🥳. You will be creating your own web server in your computer. This might sound a little complicated, but let me tell you it is not (well... not too much 😝).

## Very important ADVICE ⚠️ (read first)
If you do not fulfill the requirements that are listed below, that does not matter. I will help you throughout this process, however it is definitely a **plus** if you do have the majority of the requirements.

## Requirements
- Basic knowledge of python
- Basic knowledge of Linux commands
- You have a laptop/desktop
- Basic knowledge of any IDE (Visual Studio Code is preferred)
- Web browser (Firefox, Chrome, Opera, Brave, etc.)

## Some nice to have concepts 👻
A web server is _in simple words_ a software dedicated to store, process, and serve web pages to users over the internet. It responds to requests from web browsers and delivers the requested web content, which may include HTML pages, images, CSS stylesheets, JavaScript files, and other resources. 

**Waaaaaait!!** are you with me? Ok let's recap a bit what I have described above:

Imagine you have a restaurant, let's call it "_La Pulga_", in this imaginary restaurant you have a front side with around 10 tables and a back side with the chefs and all the people in the kitchen preparing those delicious dishes.

The Django web server (better known as well as a **backend web server**) represents the... yeeeess!! You guessed it!! It represents the back side of "_La Pulga_" restaurant. 

It will handle the requests from the customers and will process them. Whether the chef decides to start the cooking, or wait for supplies that are being delivered by a truck. This massive number of tasks to be perform and coverd are done in the **"backend server"** (Django is a backend web famework). All the logic, supplies storing, administration and distribution of some tasks are defined and build in the back side of our restaurant (the backend server).

##Let's get started
Install Visual Studio Code (VSC) on your computer. Click on this link and download VSC according to your Operative System.

{% embed https://code.visualstudio.com/download %}

Verify whether you have Python installed on your machine or not. You can do this by opening the terminal and typing:

**For Windows**
 - Click on Windows searcher, and type "CMD". Hit enter and then type:

`python --version`

**For MacOS & Linux based OS**
 - Search for an app called "Terminal", open it up and then type:

`python3 --version`

**If you do not have Python installed, do the following steps:**

Go the the [Official Python Website](https://www.python.org/) and install Python according to your OS (Windows, MacOs or any other Linux based like Ubuntu)

![Python installation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vbt8dvprcrgeh1s3fvw5.png)

If you encounter any problems, you can follow up this video: [Python Installation](https://youtu.be/8Peh7k5Sf1I?si=KifFVhnTUufEQ4IZ)

Once you have completed the installation of python, we are ready to go.

We need to create a folder to host our project. You can do it wherever you want, but for purposes of this video we will be creating it in the _/Desktop_ folder. The name we are going to give to our folder is: "django-project" (you can freely modify this name)

For **Windows** you can do it on the _CMD_. You can create a folder on the Desktop by right clicking the mouse and selecting on _Create New Folder_:

**On CMD terminal (Windows)**
`mkdir django-project`

For **MacOS/Linux** you will type the following commmand:

**On Terminal (MacOS/Linux)**
`mkdir django-project`

Hahaha!! 😂 yes, the "make directory" command is the same on MacOS, Windows and Linux.

Well, now we need to move into our new directory by typing the following command:

**Windows CMD Terminal**
`cd django-project`

**MacOS/Linux Terminal**
`cd django-project`

Ohh yeeah! Still the same command 😂 (Remember that some systems might be case sensitive).

Yeeees! The funny part is about to begin.

Before installing Django on our computer we need to create something called **Virtual Environment**, this is done to isolate different dependencies that your computer has. By doing this, you will avoid future version collisions and it will save you **TOOOONS** of headaches (_believe me!!_)

![Python virtual environment](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j69o27wgv6t9pgkvrb0j.jpg)

To create our Python Virtual Environment, we need to execute a Python module that is called _venv_ and pass to it an argument so that we can name our virtual environment. A little confusing? Hmmmm yes, a bit. Watch the command we are going to type so that you can understand it better.

This is how it would look like:

`python -m venv [the_directory_name_goes_here]`

The name we are going to give to our virtual environment is going to be **"tutorial"**.

**Windows CMD Terminal**
`python -m venv tutorial`

**MacOS/Linux Terminal**
`python3 -m venv tutorial`

> **NOTE:** When creating virtual environments is very common to name the virtual environment _venv_ or _env_, so the command to create it in that way would be: `python -m venv venv` or `python -m venv env`.

Now once we have created our virtual environment (tutorial) we can install Django... **NOOOO‼️ WE NEED TO _ACTIVATE IT!!_**

> **NOTE:** Remember to always activate the virtual environment **BEFORE** installing external dependencies (like in our case with Django).

Alright let's activate that environment:

**Windows CMD Terminal**
`tutorial\Scripts\activate.bat`

**MacOS/Linux Terminal**
`source tutorial/bin/activate`

When you do that, you will notice some sort of icon or text that displays the name of our virtual environment (tutorial).

If you do not see it, we can test that we have successfully created our virtual environment by executing the following command:

`pip freeze` or `pip3 freeze`

By doing this our output should be **emtpy** just like this:

![Pip freeze on terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/67p1w3ovrgl77xw78cze.png)

Now that our virtual environment is successfully activated we are able to download **Django**. We need to type the following command:

`pip install django`

> **NOTE:** The command **pip** stands for _Pip Installs Packages_

We obtain the following on terminal:

![Installing Django](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lm8c9sy0s1awjm37xtav.png)

Now to verify that we have successfully installed Django, we can run the command `pip freeze` to list our dependencies in our current environment. We get the following:

![Pip freeze to see Django version](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5h6593d7mrya3hssf18j.png)

Do not worry about the other two dependencies installed. The important thing here is that Django appears, in my case I have the Django version 5.0.1.

Now we can execute some of the Django commands that will allow us to create our Django Project:

`django-admin startproject la_pulga`

With this command, django will generate the necessary files to start up our project. Remember that Django is a Framework to develop fast, robust and scalable web apps in a considerable small amount of time.

After executing the command we get this:

> **NOTE:** To list the files or folders inside of the directory we are in, we can use the `ls` command.

![Django files generated](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aegxxj2mofexh7ynclz7.png)

We can see that we have a directory called **"la_pulga"**, that is super cool!! 😎. Now we need to `cd` into that folder to see the inside.

Execute the following command to get into **la_pulga**:

`cd la_pulga`

List the content of **la_pulga**.

![Listing Django content](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zh9ylpah5mna8n17446k.png)

**SUPER COOL!!😎**

Even before editing any file, we can actually run our backend web server on our local machine. **ARE YOU READY??!!**

Execute the following command:

**Windows CMD Terminal**
`python manage.py runserver`

**MacOS/Linux Terminal**
`python3 manage.py runserver`

![Django server running](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yzowxmwync67sdt80s1a.png)

Just like the image says **Yes Sir!!!**, now copy that url address `http://127.0.0.1:8000/` and open it on your web browser... and see the real magic.

![Django server opened on browser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8q6k2x33dzt6x8r8y13l.png)

We have successfully run our Django server.

To continue, we are going to quit the server by executing `CONTROL + C` (this works fine inn MacOS, Windows or Linux).

Let's edit some files to change the default Django message that appears on the browser.

Open Visual Studio Code from the terminal by executing the following command (you can open up Visual Studio Code as well from your app searcher):

`code .`

A message that says _"Do you trust the authors of the files in this folder?"_ might prompt out to your screen, click on **Yes, I trust the authors**.

![VSC message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yux2op7m4bwnfvykkjp0.png)

Then you will see your files and folders in VSC, just like this:

![Visual Studio Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3etpz0d07i5h99i3cs5a.png)

**Ufff!! So far so good?**

Alright! In Django we can create a project, and inside of that project (_la_pulga_) we can create something that Django defines as **"Apps"**. We can have as many apps as we want and the cool thing here is that we can share those "apps" with different project. With this concept in mind we apply a very important concept called **DRY (DON'T REPEAT YOURSELF)**. This is one of the features that makes Django so powerful and scalable.

**But what is an app?**

An app is basically a folder/directory that holds files. These files perform certain logic that powers up the project we are creating.

Let's create our first app. Change form VSC to the terminal and type the following command:

**Windows CMD Terminal**
`python manage.py startapp myapp`

**MacOS/Linux Terminal**
`python3 manage.py startapp myapp`

We now have a directory called "myapp":

![Django app on terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3at57v5znrno12vh44kq.png)

We now need to add this app into our project `settings.py` file. Scroll down until you se the `INSTALLED_APPS` constant.

> **NOTE:** A constant is like a variable in python. The difference is that once the code is running, its value cannot change or be updated.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ariojff58k1ufb22c0pb.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vq66mqnvwkp0jur2cfv4.png)

Next step is to create a new file called `urls.py` inside of the _myapp_ folder. Make sure you click on the _myapp_ folder and it opens up.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ron8k1igv7mixybhoe74.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oio2ryb542tx575yfdoc.png)

Inside of the file `myapp/views.py` add this code to it:

```python
from django.urls import path
from django.http import HttpResponse

# Create your views here.
def home(request):
  return HttpResponse('This is La Pulga Restaurant')
```

![Views file code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eiscpj34uiy3t9es1z6y.png)

In these lines of code we are importing the function `httpResponse` from `django.http` to display a string of text.

Let's move to the `myapp/urls.py` file. Add the following code to it:
```python
from django.urls import path
from . import views

urlpatterns = [
  path('tutorial', views.home, name='tutorial_path')
]
```

![Urls file code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xw79rnab5enaw7mjkgdq.png)

In this code we are importing the `path` function. This function will allow us to execute a logic whenever the url defined in the `path` function gets executed. We have defined the following url path:

`tutorial` --> `http://127.0.0.1:8000/tutorial`

Alright!🤩

Let's execute our server to see the results (on you terminal):

```bash
python3 manage.py runserver
```

Go to the url `http://127.0.0.1:8000/tutorial` and hit **ENTER**:

![Django 404 error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vdjuteuxtxx8hrk32afn.png)

**Ooooops🙊!!**

Alright, alright! Let's see what is going on:

> **NOTE:** This will be you one of your mainly tasks as a software engineer/developer. You need to learn how to read and overcome obstacles, bugs or errors. Good luck buddy!!

This is a **404** error which means that the error was made by the client (by us, client --> our browser), like a bad url typing or something like that. This is correct, however Django is giving us a message that gives us a clue about the error. This is the message:

![Django error message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1kna0qtj88ymwvqnekbz.png)

It says that Django tried only the url `admin`. This is kind of wrong, right? Because we defined the `tutorial` url, but Django is not recognizing it.

We need to update the `la_pulga/urls.py` file with the following code to let know Django that should include the **_urls.py_** file defined inside of the app **_myapp_**:

```python
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls'))
]
```

![la_pulga urls file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jh4w2alh3e17nsxjarhf.png)

As you can see we have the `/admin` url path, and now we just added the ulrs from our app called **myapp**. We defined an empty string in the first parameter of the **path()** function to let know Django that `myapp/urls.py` will handle all the url paths that start from the root `/`.

> **NOTE:** The root url `/` is for example: **https://facebook.com/** <-- (this is the root path). A sub route would be **https://facebook.com/profile**.

Now let's check again the url `http://127.0.0.1:8000/tutorial` (remember that you need the server running). And we get:

![Success in the browser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2n76ws9hgqy3wdlb7gqu.png)

**YEEEESSS!! WE GOT IT!! 👏🙌**

You have created your own Django Backend Web Server in your computer and display a simple string of text.

**Tech stuff is very important 🚨**
You will need to learn about programming and the basis of software development. Nowadays, we consume all the time technological products (tangible and intangible). Whether you are studying medicine, arts, chemistry or mechanics, programming will be a **MUST TO** learn (or already is).

---

## Please share this tutorial 🙏😉

It'll be super cool if you dedicate 2 minutes of your time to copy the link and share it with you classmates and friends. **Let's make a help chain**.