django 如何导入www.example.com的多个视图urls.py?

piok6c0g  于 2022-12-14  发布在  Go
关注(0)|答案(3)|浏览(150)

我需要从星座和日期导入视图,但是当导入到urls.py时,出现了冲突,因为只有一个视图被感知。
所以我的问题是:如何导入多个视图?
我尝试了几种方法,例如:

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),
]

还有这个

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),
]

但这两个选项仍然忽略其中一个视图。

v2g6jxz6

v2g6jxz61#

正如voodoo-burger所建议的,浏览器一次只能显示一个页面,所以要么将你的URL重命名为更具体的名称,以便区分不同的视图,要么你正在寻找URL Namespacing
来自Django文档:

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'),
    ...
]

然后按如下方式调用您的URL:

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

tzdcorbm2#

您可以尝试以下代码

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),
]
zxlwwiss

zxlwwiss3#

我找到了解决问题的最佳方案,它包括在每个应用程序www.example.com中创建一个单独的文件urls.py,分别以下面的形式添加所有URL地址:
在我的每一个应用程序中,我添加了一个名为www.example.com的独立文件urls.py,并输入了以下内容:

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),
 ]

并根据同样的场景,我为另一个应用程序添加了url

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

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

主要的一个包括应用程序urls.py,它看起来像这样:

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")),
]

相关问题