Djang 视图和 url 连接

Djang views and urls connect

提问人:Hyun Kim 提问时间:11/15/2023 最后编辑:SelcukHyun Kim 更新时间:11/15/2023 访问量:72

问:

应用文件夹 :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.
python django django 视图 django-urls

评论


答:

4赞 Selcuk 11/15/2023 #1

您没有为空路径定义路由(即 )。当您包含其他应用的 URL 定义时,这两个路径是串联的,因此目前项目中唯一有效的路径是:http://<hostname>/

'' (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'),
1赞 user22918388 11/15/2023 #2

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

# views.py
from django.http import HttpResponse

def hello_world(request):
    return HttpResponse("Hello, World!")
# urls.py
from django.urls import path
from .views import hello_world

urlpatterns = [
    path('hello/', hello_world, name='hello_world'),
]