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?
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?
On
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!
On
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.
Mostly for reusability, partly for organizational reasons. Separate
urls.pyfiles allow django apps to be portable between projects. If you ship an app with theurls.pythen 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.siteapp that ships with Django itself. Theadmin.siteapp supplies its ownurls.pyfile, so you are able to easily just add to your own project's url patterns.Like this:
If the
admin.siteapp didn't have its ownurls.pyfile, 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.pyfile. You can use that alone, if you really want to.