用Django寫第一個頁面hello與hello xxx
首先創建Django項目
_init_.py初始化文件
settings.py 項目的設置/配置
urls.py路由配置文件(URL分發器)
urlpatterns = [
url(正則表達式, view函數, 參數, 別名, 前綴),
]
1:不帶參數
urlpatterns = [
url(r'^hello/$',hello),
]
2:帶參數
urlpatterns = [
url(r'^hello/$', hello, {'name':'Gudolf'}),
]
正則表達式
r是raw的簡寫,rawstring 意思是這個字符串中間的特殊字符不用轉義。
比如表示‘\n’,可以這樣:r'\n'
但是如果你不用原生字符 而是用字符串你得這樣:‘\\n’
^為匹配輸入字符串的開始位置。
$為匹配輸入字符串的結束位置。
view.py視圖
不帶參數
from django.shortcuts import render
defhello(request,name):
context? = {}#創建字典
context['hello'] ='Hello'#為字典添加元素
returnrender(request,'hello.html',context)
帶參數
from django.shortcuts import render
defhello(request,name):
context? = {}#創建字典
context['hello'] ='Hello '+name#為字典添加元素,name為傳遞的參數
returnrender(request,'hello.html',context)
這里用到了render方法
render(request, template_name, context=None, content_type=None, status=None, using=None)
Returns a HttpResponse whose content is filled with the result of calling?django.template.loader.render_to_string() with the passed arguments.
此方法的作用---結合一個給定的模板和一個給定的上下文字典,并返回一個渲染后的 HttpResponse 對象。
通俗的講就是把context的內容, 加載進templates中定義的文件, 并通過瀏覽器渲染呈現.
參數講解:
request: 是一個固定參數, 沒什么好講的。
template_name:?templates 中定義的文件, 要注意路徑名. 比如'templates\polls\index.html', 參數就要寫‘polls\index.html’
context: 要傳入文件中用于渲染呈現的數據, 默認是字典格式
content_type:生成的文檔要使用的MIME 類型。默認為DEFAULT_CONTENT_TYPE 設置的值。
status: http的響應代碼,默認是200.
using:?用于加載模板使用的模板引擎的名稱。
hello.html
<!DOCTYPE html>
<html lang="en">
<head>
? ? <meta charset="UTF-8">
? ? <title>Title</title>
</head>
<body>
? ? <h1>{{hello }}</h1>
</body>
</html>
運行project
訪問 :http://127.0.0.1:8000/hello/