Right now, all of the urls we have in our Django project is placed inside the urls.py file in our main folder. This isn't the best solution, because the file can be very long and unmaintainable. It also doesn't make much sense to import all of the view to this file.
So what we want to do now is to create separate urls.py file for the apps. One for the task app and one for the category app.
Create a new file called urls.py inside the task app. It should look like this:
from django.urls import path
from . import views
urlpatterns = [
path('', views.frontpage, name='frontpage'),
]
As you can see, this is the same path as we used in our main urls file. Only difference is that we added a "views." infront of the view name. You can now remove this url from the main urls.py file.
Next, let's do this for the category as well. That file should look like this:
from django.urls import path
from . import views
urlpatterns = [
path('<int:pk>/', views.category_detail, name='category_detail'),
]
So you can now remove this from the main file as well.
The problem now is that Django doesn't know that these urls exists any longer. So if you visit the site now, you will get a 404 error.
To fix this, we can import these two files to the main urls.py file. It should look like this:
from django.urls import path, include # Change, 1
urlpatterns = [
path('', include('task.urls')),
path('', include('category.urls')),
]
What happens now is that if you go to the front page, it will first go into the urls in the task app. And yes, it will find the front page and render it.
If you go to "/1/", it will first go into the urls file in the task app. But there isn't any paths that will match. So it will continue to the category app, and there it will find the category detail page.
Maybe the main urls.py doesn't look much cleaner right now, but as soon as we start adding more pages to the different apps, you will understand why we do this.
Table of contents
- 1. Introduction
- 2. Installation and setup
- 3. How things work
- 4. The first Django app
- 5. Your first view
- 6. Your first template
- 7. Testing our site
- 8. Extending templates
- 9. Your first model
- 10. The admin interface
- 11. Showing contents from the model
- 12. Another app (category)
- 13. Connecting two models
- 14. Show list of categories
- 15. Category detail page
- 16. Separate url files and why