pythondjangourl-mapping

In django what is the use of urls.py for each app?


I am making a django project and i learnt that we need to create a urls.py file for each app created within project.

Can anyone please tell what is the purpose of this because we have one urls.py file for the main project, isn't that enough?


Solution

  • Mostly for reusability, partly for organizational reasons. Separate urls.py files allow django apps to be portable between projects. If you ship an app with the urls.py then it can be used easily in many different Django projects. This is covered in the Reusable Apps section of the official tutorial.

    For example, the Admin site is provided by the reusable admin.site app that ships with Django itself. The admin.site app supplies its own urls.py file, so you are able to easily just add to your own project's url patterns.

    Like this:

    urlpatterns = [
        path('admin/', admin.site.urls),
        # ...
    ]
    

    If the admin.site app didn't have its own urls.py file, this wouldn't be possible.

    The admin app is just one example. There are many apps that are distributed on PyPI and are installable with pip.

    That said, it's not entirely necessary. Like you point out, there is a project level urls.py file. You can use that alone, if you really want to.