Django Views and URLs Explained
Tags: django, python, programming, tutorial
Published: 2023-08-30 15:32:23

It's common across web frameworks to spin up a development server and see the preview of a demo site in your browser. Django gives us the ability to do so. 

In this guide, we'll create an app using Django Views and URLs to display the result in a web browser.

Let's get started.

## Source code
Find the complete source code in [this repository](https://github.com/Terieyenike/django-projs/tree/main/first_proj).

## Django project setup
Before the project setup, ensure you have Python 3 installed on your local machine. To check, run this command:

```zsh
python --version // Python 3.11.4
```

**Create a folder**
Use the command `mkdir` to create a new directory.

```zsh
mkdir first_proj
```

Next, navigate into the project directory and run the Python virtual environment:

```zsh
cd first_proj

python -m venv .
```


**Activate the virtual environment (venv)**
In the `zsh` on macOS, run this command to activate the **venv**.

```zsh
source ./bin/activate
```

The terminal should look this:


![activated virtual environment](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/he0bikarv2bpqkgyjpzz.png)



> For other shell command users, check [this guide](https://docs.python.org/3/library/venv.html).

**Install Django**
Using the `pip` command which comes pre-built when you have Python installed, type this command in your CLI (command line interface):

```zsh
pip install django
```

Now, to check Django is present locally, run:

```zsh
pip list
```

**OR**


![check django version](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wjncc7qdi9nrhy2u9bnx.png)

**Creating a project**
Run the command below in your root directory that creates a collection of settings for an instance of Django, including database configuration, Django-specific options, and application-specific settings.

```zsh 
django-admin startproject config .
```

The period (.) represents the folder **config** creation in the root of the `first_proj` directory.

> Remember to complete this step.

**The development server**
The last step of the project setup is to verify that your Django project works.

Run the command:

```zsh
python manage.py runserver
```

The `runserver` command starts the development server on port `8000`, the internal IP address during development.

## Adding URLs and Views
To create URLs and Views, you need to create a Django app. That means a Django project consists of one project in the **config** and one or more Django apps.

Run this command to create one:

```zsh
python manage.py startapp my_app
```

**Register the app**
Go to the `settings.py` file in the **config** folder, and under the installed apps list, add "my_app".

```python3
...
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

    "my_app",
]
...
```

**How do the URLs and Views work?**

A request in Django comes from the `urls.py`, and if it matches with the endpoints set and the views Python function from the `views.py` file, it gives the response to the **templates** to display the result. 

- A `view` is a Python function or class-based views defined in the `views.py` file.

- The `urls.py` file tells Django the path on our site to call the view.

Let's define some views and URLs.

Open the following files, `views.py` and `urls.py`, in the **my_app** and **config** folders.

Copy-paste this code:

`my_app/views.py`
```python
from django.shortcuts import HttpResponse

# Create your views here.
def index(request):
  return HttpResponse("Hello world!!!")


def about(request):
  return HttpResponse("Visit my page on https://iamteri.tech")


def hello(request, first_name):
  return HttpResponse(f"Hello {first_name}")


def calculate(request, num1, num2):
  return HttpResponse(f"The total is {num1+num2}")
```

For each view above, it returns an **HttpResponse** object containing the content for the requested page.


`config/urls.py`
```python
...
from my_app.views import index, about, hello, calculate

urlpatterns = [
    ...,
    path("", index),
    path("about/", about),
    path("hello/<str:first_name>/", hello),
    path("calculate/<int:num1>/<int:num2>/", calculate)
]
```

The code above does the following:

- Import all the defined views function in the `views.py` file
- In the **urlpatterns** list variable, the path URL maps to each of the Python callback functions (views)

Check the result in the browser.

Once again, restart the development server if it is not running:


```zsh
python manage.py runserver
```

Go to the home route, `http://127.0.0.1:8000`, which should look like this:


![Home route template](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0recx8p2vjvededllwzz.png)

Another route using the URL, `http://127.0.0.1:8000/calculate/2/3/`


![Calculate two numbers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7bjjupabcpw61bhtqme5.png)

Try the others to see the result.


## Conclusion
In this tutorial, you've learned how to start a new Django project and now better understand how to display a response using URLs and Views.


## Resources

- [Understand the MVT pattern](https://dev.to/terieyenike/what-is-django-first-impressions-3m60)
- [How Django processes request](https://docs.djangoproject.com/en/4.2/topics/http/urls/#how-django-processes-a-request)
- [How venvs work](https://docs.python.org/3/library/venv.html#how-venvs-work)