Separate url files and why - 30 days of Django

Separate url files and why - 30 days of Django

/ #Django


Learn how and why it's important to have separate urls.py file for each of the Django apps

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

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.