Django(三)url和返回


location 最后一個文件夾名就是project名,我用了Django_Plan。

Application 是自動加入的APP名字,我用了Plan

編輯Django_Plan\Django_Plan\urls.py

from django.contrib import admin
from django.urls import path
from Plan import views

urlpatterns = [
path('admin/', admin.site.urls),
path('plan', views.plan) #此行為增加的
]

編輯Django_Plan\Plan\views.py

from django.shortcuts import render
from django.shortcuts import HttpResponse  #此行增加
# Create your views here.
def plan(request):                   #此函數增加
    return HttpResponse('hello')

好了,我們增加了一個url解析,解析到plan函數,進行http返回給瀏覽器。

試一下,瀏覽器http://localhost:8000/plan,會看到hello。用的是HttpResponse函數。

平時訪問的頁面那么多內容,我們不能都寫在HttpResponse中呀。

我們用模板吧。

 

建立一個hello.html文件放在Django_Plan\templates\hello.html

內容為:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<h1>hello</h1>    
</body>
</html>

編輯Django_Plan\Plan\views.py

from django.shortcuts import render
from django.shortcuts import HttpResponse  #此行增加
# Create your views here.
def plan(request):                   #此函數增加
    return render(request,'hello.html')

 

檢查Django_Plan\Django_Plan\settings.py(難道我用最新的django2.0,pycharm就不自動創建了?)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],    #注意此行
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

 

好了,這下瀏覽器返回的就是我們的模板文件內容,h1格式的hello

我們還需要動態生成頁面,繼續編輯hello.html,給輸出的hello加上兩個大括號

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<h1>{{ hello }}</h1>
</body>
</html>

 

編輯Django_Plan\Plan\views.py

from django.shortcuts import render
from django.shortcuts import HttpResponse  #此行增加
# Create your views here.
def plan(request):                   #此函數增加
    return render(request,'hello.html',{'hello':'hello jack'})

這里就是在render的參數中又加了一個字典,把hello換成hello jack,再返回給客戶端瀏覽器。

打開頁面試試吧。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM