I'm new to coding so excuse me if this was a silly question but I couldn't find a clear answer anywhere. So I have a django project with two apps inside it, both of them has the root '/',what is the exact format and implementation to use return redirect('/')to let django differentiate between these two roots in different apps maybe using naming routes. a step by step guide will be appreciated, thank you in advance.
CodePudding user response:
For example you have a django project called InitialProject and the project has 2 apps inside, let's call them MyApp1 and MyApp2.
Your directory structure should look something like this:
PythonProject/
├─ InitialProject/
│ ├─ __init__.py
│ ├─ asgi.py
│ ├─ settings.py
│ ├─ urls.py
│ ├─ wsgi.py
├─ MyApp1/
│ ├─ migrations/
│ ├─ filters.py
│ ├─ tests.py
│ ├─ urls.py
│ ├─ views.py
│ ├─ models.py
│ ├─ __init__.py
│ ├─ admin.py
│ ├─ apps.py
├─ MyApp2/
│ ├─ migrations/
│ ├─ filters.py
│ ├─ tests.py
│ ├─ urls.py
│ ├─ views.py
│ ├─ models.py
│ ├─ admin.py
│ ├─ __init__.py
│ ├─ apps.py
So firstly, URLs are unique, that is 1 URL can only lead to one path or one views function in this case. But what we can do is that we can say that URL starting with 'APP1' should look into MyApp1/urls.py for the function and URL starting with 'APP2' should look into MyApp2/urls.py
So in InitialProject/urls.py, we define it as follows:
from django.urls import path
from django.urls.conf import include
urlpatterns = [
path('APP1/', include('MyApp1.urls')), # Note the trailing forward slash, it is important
path('APP2/', include('MyApp2.urls')),
]
So, what this does is that is: if your URL is: HTTP://localhost/APP1/ it will tell Django to look into MyApp1/urls.py to resolve and get the function and similarly for APP2.
Now in MyApp1/urls.py we can do is that:
from . import views
from django.urls import path
urlpatterns = [
path('', views.my_function_1), # This URL will resolve as HTTP://localhost/APP1/
path('second_url', views.my_function_2), # This URL will resolve as HTTP://localhost/APP1/second_url
]
And similarly can be done for MyApp2. By this method, you have a cleaner URL structure and it is also easy to navigate and see which app is being called.
I hope you are able to understand how URL Patterns work.
You might as why did we define the initial URL pattern in InitialProject/urls.py? Because by default Django will first go to the project directory to see which URL patterns and from there only we can link other App's URL patterns.