Shivang Gautam
Shivang Gautam

Reputation: 53

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?

Upvotes: 0

Views: 2428

Answers (3)

Fonij
Fonij

Reputation: 11

If you place all your website urls’ in the main urls.py of the project, the file can get very long and the maintenance and change can be very hard, also you have to import all the views into this one file. On the other hand, separate urls.py allows you to use the same app with different URL patterns in different projects.

Upvotes: 0

Manoj Tolagekar
Manoj Tolagekar

Reputation: 1960

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!

Upvotes: 0

sytech
sytech

Reputation: 40861

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.

Upvotes: 1

Related Questions