Why do we direct the urls file in our main directory to the newly created urls file in the app directory in Django?

288 Views Asked by At

I was learning Django and noticed people directing the URLs file in the main directory of the project to a new created URL.py file in the app folder? Why can't we directly put the path in the URL file in the main directory? Pre-existing URL.py file New created URL.py file in app folder

Instead of using include, we could have directly put the path there. Why aren't we doing it?

1

There are 1 best solutions below

0
Aman Garg On

Keeping URLs in separate apps provides certain advantages:

  1. Maintain hygiene for each app. You get to manage all the URLs of a particular app in its own urls.py rather than managing all URLs in the same main urls.py file, which will be a hassle as the size of the project grows.
  2. Using namespace. If you have similar URLs in two different apps - like a create endpoint in API, and a create endpoint for UI, you can just use the namespace to uniquely refer to them without creating any confusion (learn more).

Let's say you want to move all URLs for an app to a different location, like from /api/ to /api/v1/, all you'll need to do is to update the main urls.py file and update the path where you include the app, instead of updating all the URLs individually!

Or you want to remove an app, then all you need to do is remove the app itself and remove one line from the main urls.py, instead of removing each URL and introducing a possibility that a URL was still left.

Creating separate apps keeps everything clean, easy to find and manage. That's why URLs for each app is kept separate and are simply included in the main urls.py file.