python測試開發django-2.templates模板與html頁
前言
Django 中的視圖的概念是一類具有相同功能和模板的網頁的集合。通俗一點來說,就是你平常打開瀏覽器,看到瀏覽器窗口展示出來的頁面內容,那就是視圖。
前面一章通過瀏覽器訪問http://127.0.0.1:8000能在頁面上展示出hello world的純文本內容,通常我們打開瀏覽器頁面,展示的是一個html頁面,本篇講下如何打開html頁面。
新建應用
上一篇通過“django-admin startproject helloworld”是創建項目,一個項目下可以有多個應用(app).打開cmd,cd到manage.py所在目錄使用如下指令創建一個應用
python manage.py startapp hello
新建成功後,生成的目錄結構如下
─hello_django │ db.sqlite3 │ manage.py │ ├─hello │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ views.py │ │ __init__.py │ │ │ ├─migrations │ │ __init__.py │ └─hello_django │ settings.py │ urls.py │ view.py │ wsgi.py │ __init__.py
setting配置
新建應用後,一定要在setting.py腳本裏面,把剛才新建的應用名稱添加到INSTALLED_APPS裏,要不然無法識別到新增的這個應用,如下最後一行。
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello' ]
templates模板
在hello目錄下新建一個templates包,再新建一個demo.html文件,寫入以下內容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo樣式</title>
</head>
<body>
<p>
<h4> 這是我的博客地址,可以百度搜:上海-悠悠 </h4>
<a href="https://www.cnblogs.com/yoyoketang/" target="_blank" >上海-悠悠-博客園</a>
<hr>
<h4> 《python自動化框架pytest》 </h4>
<p>pytest是最強大最好用的python自動化框架,沒有之一。本書詳細講解pytest框架使用方法,fixture功能是pytest的精髓,書中有詳細的案例講解。<br>
另外最後會有項目實戰代碼,靈活用到selenium自動化項目上。<br>
pytest交流群874033608
</p>
<a href="https://yuedu.baidu.com/ebook/902224ab27fff705cc1755270722192e4536582b" target="_blank" >百度閱讀地址點此</a>
</p>
</body>
</html>
關於html相關語法學習,可以參考這個網站【http://www.runoob.com/html/html-tutorial.html】
視圖與url
html的內容頁面有了,接下來就是如何能讓他在指定的url地址上展示出來了,在hello/views.py裏寫視圖函數
在hello/views.py裏寫視圖函數
from django.shortcuts import render
# Create your views here.
def demo(request):
return render(request, 'demo.html')
在helloworld/urls.py裏添加url訪問路徑
from django.conf.urls import url
from . import view
from hello import views
urlpatterns = [
url('^$', view.index),
url('^yoyo$', view.yoyo),
url('^demo$', views.demo)
]
pychram裏面from hello import views這個導入會報紅,不要問我為什麽,我也不知道,反正運行不會報錯
接下來在瀏覽器輸入地址:http://127.0.0.1:8000/demo就能訪問到demo.html頁面啦
python學習交流QQ群:588402570
python測試開發django-2.templates模板與html頁