user12206273
user12206273

Reputation:

what are the differences between urls.py in project's folder and app folder in django?

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 ?

Upvotes: 5

Views: 3702

Answers (1)

Ewaren
Ewaren

Reputation: 1763

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.

Upvotes: 9

Related Questions