4

In django there is a concept that makes me dazzled a bit.Why we should make a urls.py in our app folder while we have one in project folder.

what is the specific job each one do ?

how both have relation with each other e.g how do they interact with each other to make a django website ?

  • @FutureJJ, I already know the difference between an app and a project in django, the problem i have is the concept of having two urls.py , one in project level and one in app level, I just want to know how do they interact with each other. –  Oct 25 '19 at 08:22
  • I'm guessing you're looking for the docs for [include](https://stackoverflow.com/q/41125909/1324033), your question is too broad for [so] – Sayse Oct 25 '19 at 08:25
  • @Sayse, I read [What’s the difference between a project and an app in Django world?](https://stackoverflow.com/questions/19350785/what-s-the-difference-between-a-project-and-an-app-in-django-world) , and because it did'nt solve my problem, I was made to ask this question . –  Oct 25 '19 at 08:31

1 Answers1

9

The urls.py in your project folder are the "base" URLs for your site. You can then forward requests made on a certain route to your app's urls.py using include.

Here is an example :

# project's urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include("myapp.urls")) # requests on a route starting with "myapp/" will be forwarded to "myapp.urls"
]

And then in myapp.urls :

# myapp's urls.py
from django.urls import path
from . import views

app_name = "myapp"

urlpatterns = [
    path("", views.index, name="index"),
    path("contact/", views.contact, name="contact")
]

So for instance, if I request "localhost:8000/myapp/contact", your project's urls.py will detect that it must forward the request to your app myapp, which will call its view views.contact.

Ewaren
  • 1,343
  • 1
  • 10
  • 18
  • if i'm right please tell me, so we have base url for our project in django, to make our apps integrated with our main project we have to have a urls.py in our app level directory and then make it's own url and simultaneously to add this or these apps to our project we have to make it accessible to our project by adding it to our urls.py in project level. Am I right ? –  Oct 25 '19 at 08:38