DEV Community

Cover image for Django Views and URLs Explained
teri
teri

Posted on

Django Views and URLs Explained

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.

Django project setup

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



python --version // Python 3.11.4


Enter fullscreen mode Exit fullscreen mode

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



mkdir first_proj


Enter fullscreen mode Exit fullscreen mode

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



cd first_proj

python -m venv .


Enter fullscreen mode Exit fullscreen mode

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



source ./bin/activate


Enter fullscreen mode Exit fullscreen mode

The terminal should look this:

activated virtual environment

For other shell command users, check this guide.

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



pip install django


Enter fullscreen mode Exit fullscreen mode

Now, to check Django is present locally, run:



pip list


Enter fullscreen mode Exit fullscreen mode

OR

check django version

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.



django-admin startproject config .


Enter fullscreen mode Exit fullscreen mode

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:



python manage.py runserver


Enter fullscreen mode Exit fullscreen mode

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:



python manage.py startapp my_app


Enter fullscreen mode Exit fullscreen mode

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



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

    "my_app",
]
...


Enter fullscreen mode Exit fullscreen mode

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



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}")


Enter fullscreen mode Exit fullscreen mode

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

config/urls.py



...
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)
]


Enter fullscreen mode Exit fullscreen mode

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:



python manage.py runserver


Enter fullscreen mode Exit fullscreen mode

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

Home route template

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

Calculate two numbers

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

Top comments (0)