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

Time:03-12

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?

CodePudding user response:

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.

CodePudding user response:

There is no difficulty to understand urls.py. It is used to create routes in the project.

routes like:

/home
/users etc.

This is not mandatory to create urls.py for each apps. you can add all apps path in urls.py in main project. It depends on you.

But creating urls.py for each app looks good format to understand.

Routes define where you are going means from one route to another.

Remember that each view must have path in urls.py. Without this, it will not appear on web page.

I hope you understood!

  • Related