How Django URL works

Asked

Viewed 280 times

0

I’m developing a Jango website.

Where I own these two structures

main

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index),
]

app

    from django.contrib import admin
    from django.urls import path
    from . import views

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

I don’t understand why referencing the URLS in both files, as it seems that I am calling the views of my project twice.

Can you explain to me the functioning of these structures?

3 answers

1

Dude, when you generate a Django project, it builds an initial structure that serves as a base for you to start using Django admin. This app is an app that Django will use, so you’ll have urls for your app (this ai app) and Django urls, and since Django is the foundation, it will call your app urls. I hope it gives to etender.

More information on: Django urls

1

I believe the main one is your main project. In the main project you have the.py urls file that routes to the urls of the various apps that you may have linked to the project.

ex :

The user accesses the site www.system.com.br The server will hit main.urls path('/', include(home_urls)) and in the app "Home" will have a file urls.py that will call the view.

Say you go to www.system.com.br/clients, the server will hit main.urls path('clientes/', include(clientes_urls)) and will be directed to the app "Customers" which also has a file urls.py with the routes referring to customers that will forward to the specific views.

from django.urls import path, include
from clientes import urls as clientes_urls
from home importe urls as home_urls

urlpatterns = [  
    path('/', include(home_urls)) 
    path('clientes/', include(clientes_urls)),  
    path('admin/', admin.site.urls),

I’m sorry if I wasn’t very clear, it’s been a while since I started studying python and Django.

0

I use it to segment my code, it is possible to put all """routes""(URLS) in a single file but would be little intuitive. So I put the URLS separately for each APP. Avoid messing with other Apps routes.

 from django.urls import path, include
 from clientes import urls as clientes_urls
 from home importe urls as home_urls

 urlpatterns = [  
     path('/', include(home_urls)) 
     path('clientes/', include(clientes_urls)),  
     path('admin/', admin.site.urls),
 ]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.