Home > Mobile >  How do I import multiple views for urls.py?
How do I import multiple views for urls.py?

Time:12-13

I need to import views from horoscopes and dates, but when importing them into urls.py there is a conflict because of which only one views is perceived.

So my question is: how do I import multiple views?

I've tried several approaches, e.g.:

from django.contrib import admin
from django.urls import path
import horoscopes
import dates
urlpatterns = [
    path('admin/', admin.site.urls),
    path('horoscopes/leon', horoscopes.views.monday),
    path('dates/monday', dates.views.monday),
]

as well as this one:

from django.contrib import admin
from django.urls import path
from horoscopes import views as horoscopes_views
from dates import views as dates_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('horoscopes/leon', views.leon),
    path('dates/monday', views.monday),
]

But both options still ignore one of the views.

CodePudding user response:

As voodoo-burger was suggesting, the browser can only display one page at the time. So either rename your URLs to more specific names in order to differentiate between the views, or you are looking for URL Namespacing.

From the Django Documentation:

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    ...
]

Then call your URL like this:

reverse('polls:index', current_app=self.request.resolver_match.namespace)

CodePudding user response:

You can try following code

from django.contrib import admin
from django.urls import path
from horoscopes import views as horoscopes_views
from dates import views as dates_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('horoscopes/leon', horoscopes_views.leon),
    path('dates/monday', horoscopes_views.monday),
]

CodePudding user response:

I found the most optimal solution to my problem and it consisted in creating a separate file in each application urls.py , separately adding all URL addresses there in this form:

in each of my applications, the necessary horoscopes and I added a separate file called urls.py and I entered the following into it:

 from django.urls, import the path
 from . import views # the dot indicates that we are referring to the directive in which the file is located

 urlpatterns = [
 path('scorpion/', views.scorpion),
 path('leon/', views.leon),
 ]

and according to the same scenario, I added to another application for the url

from django.utils, import the path
from . import views

urlpatterns = [
path('monday/', views.monday),
]

The main one includes the application urls.py it looks like this:

from django.contrib, import admin
from the django.utils import path, including

urlpatterns = [
path('admin/', admin.site.urls),
path('horoscopes/', include("horoscopes.urls")),
path('dates/', include("dates.urls")),
]
  • Related