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
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
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
Our second view:
Mapping it to a URL:
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
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
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
The views
Top comments (0)