DEV Community

Abby Nduta
Abby Nduta

Posted on • Edited on

Mapping URLs to views in Django: Simple version

Well, how about mapping views to URLs in Django?

A simple way to think about URLs is simply as paths or pages on a website.

On a website, you can have home, about, and contact pages,
for example.

You could put it like this in terms of folder structure:

    Website
    ├── Home
    ├── About 
    ├── Contact
Enter fullscreen mode Exit fullscreen mode

Once you have created a Django project and App directory, and ran the 'python manage.py runserver' your home page is http://127.0.0.1:8000/

If you want to access another page, the 'about' page for example, then your path would be 'http://127.0.0.1:8000/about'

The 'contact' page path would be 'http://127.0.0.1:8000/contact'

But how would this look like in terms of the views you need to create and how would you map them to their specific URLs in Django?

Assumptions

I assume that you have already created a templates directory and created the above pages inside it, and done all the configurations in your settings.py

Mapping views to URLS the redundant way

Our first view:

In the views.py module in your App directory

Image description

This first view belongs to the home page (http://127.0.0.1:8000/)

Mapping it to a URL:

In the urls.py module in your project directory

Image description

Image description

Our second view:

Image description

Mapping it to a URL:

Image description

Image description

You get the gist. You'd have to do this for each of those file paths.

Imagine if you had 10 of those paths. Then you'd have 10 url patterns in your project's urls.py module. What would happen if you had three App directories?

Or if page had subpages?

That's a lot of url patterns.

The include() function

We can "group" URLs per app.

Let's say that our first path is "/AppTwo". Our folder structure would be:

    Website
    ├── Home
    ├── AppTwo 
    ├── AppThree
Enter fullscreen mode Exit fullscreen mode

We can then have subpages under "/AppTwo"

Your home page is still http://127.0.0.1:8000/

The AppTwo path would be 'http://127.0.0.1:8000/AppTwo'

The 'about' page path would be http://127.0.0.1:8000/AppTwo/about'

Let's create the views and map them to URLs.

The AppTwo url mapping

Image description

We'll also have an additional url mapping in the App directory urls.py

This will show all url patterns in the App directory, which is our "AppTwo/" path

Image description

The views

Image description

Image description

Top comments (0)