python Djang视图和URL连接

t1qtbnec  于 2023-11-15  发布在  Python
关注(0)|答案(2)|浏览(74)

应用程序文件夹views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def MyApp(request):
    return HttpResponse("HELLO APP")

字符串
应用程序文件夹urls.py

from django.urls import path
from . import views

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


项目文件夹urls.py

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

urlpatterns = [
    path('', include('MyApp.urls')),
    path("admin/", admin.site.urls),
]


当尝试打开http://127.0.0.1:8000时,我得到以下错误:

Using the URLconf defined in FirstProject.urls, Django tried these URL
patterns, in this order: MyApp/ [name='MyApp'] admin/ The empty path
didn’t match any of these.

bxgwgixi

bxgwgixi1#

您没有为空路径(即http://<hostname>/)定义路由。当您包含另一个应用的URL定义时,两个路径会连接在一起,因此当前项目中唯一有效的路径是:

'' (from main urls.py)  + '/MyApp/' (from app/urls.py)
'admin/` (from main urls.py)

字符串
更改以下行

path('MyApp/', views.MyApp, name='MyApp'),


path('', views.MyApp, name='MyApp'),

wkyowqbh

wkyowqbh2#

要连接Django视图和URL,您需要在urls.py文件中为每个视图定义一个URL模式。

# views.py
from django.http import HttpResponse

def hello_world(request):
    return HttpResponse("Hello, World!")

个字符

相关问题