django學習筆記(四)—簡單跑通django項目

通過前三篇的瞭解,大概知道了django是幹嘛的,現在可以開始操作了

首先在Helloworld目錄下新建一個view.py文件

from django.http import HttpResponse

def hello(request):
    return HttpResponse("This is my first project")

然後在url.py文件下需要配置

from django.urls import path
from . import view

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'',view.hello)
]

【踩坑】需要把view引入,要不會報錯

運行起來,頁面上就會加載

上面還沒有涉及到template

OK,可以直接分離頁面和數據了,下面添加templates部分

(1)在項目下新建文件夾templates

【備註】此處踩坑把templates文件夾建到2裏面,導致運行的時候怎麼都找不到hello.html

 修改view.py文件

from django.shortcuts import render

def hello(request):
    context = {}
    context['hello'] = "hello world"
    print("ddd")#此處是爲了查服務器一直異常的問題,定位到是問題是找不到hello.html
    return render(request, 'hello.html', context)

添加hello.html文件

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>djangoTest</title>
</head>
<body>
    <h1>{{hello}}</h1>
    <p>Django 測試</p>
</body>
</html>

刷新頁面http://127.0.0.1:8000/hello/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章