Python Django 通用視圖和錯(cuò)誤視圖的使用代碼
定義通用視圖
修改 book/models.py
代碼中的 AuthorInfo
類,如果一致則不必修改
class AuthorInfo(models.Model): id = models.CharField(max_length=30, verbose_name="身份證號", primary_key=True) name = models.CharField(max_length=20, verbose_name="姓名") telephone = models.CharField(max_length=20, verbose_name="聯(lián)系方式") age = models.IntegerField(verbose_name="年齡", default=30) sex = models.CharField(max_length=2, verbose_name="性別", default="男") def __str__(self): return self.name
在 book/views.py
文件下新建 AuthorListView
的函數(shù)
from book.models import AuthorInfo from django.views.generic.list import ListView class AuthorListView(ListView): model = AuthorInfo template_name = "list.html" context_object_name = "my_author"
在 book/urls.py
的 urlpatterns
列表中新建一個(gè)路由
path('author/', views.AuthorListView.as_view())
新建 templates/list.html
文件
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <ul> {% for item in my_author %} <li>{{ item.name }}</li> {% endfor %} </ul> </body> </html>
訪問 http://127.0.0.1:8000/book/authorlist/
如果無法訪問頁面,請檢查 chapter1/urls.py
文件內(nèi)的 urlpatterns
列表中是否含有 book
的路由
如果為無報(bào)錯(cuò)且為空白頁面,請注意查看數(shù)據(jù)庫內(nèi)是否含有數(shù)據(jù),下面為添加示例數(shù)據(jù)的代碼
INSERT INTO book_authorinfo (id, name, telephone, age, sex) VALUES ('a001', 'Alice', '13812345678', 25, 'F'), ('a002', 'Bob', '13987654321', 30, 'M'), ('a003', 'Charlie', '13611112222', 40, 'M'), ('a004', 'David', '13533334444', 20, 'M'), ('a005', 'Eve', '13755556666', 35, 'F');
可在此處執(zhí)行
如無問題,將會(huì)看到作者信息
定義錯(cuò)誤視圖模板
修改 chapter1/settings.py
文件
DEBUG = False ALLOWED_HOSTS = ['*']
新增 templates/404.html
文件
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>此頁面未找到</title> </head> <body> <h2>自定義的404頁面</h2> <p>您訪問的頁面不存在</p> </body> </html>
此時(shí)進(jìn)入未定義的路由網(wǎng)址時(shí),便會(huì)顯示上面編寫的網(wǎng)頁
到此這篇關(guān)于Python Django 通用視圖和錯(cuò)誤視圖的使用的文章就介紹到這了,更多相關(guān)Python Django視圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python3+pyqt5+itchat微信定時(shí)發(fā)送消息的方法
今天小編就為大家分享一篇python3+pyqt5+itchat微信定時(shí)發(fā)送消息的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02numpy如何按條件給元素賦值np.where、np.clip
這篇文章主要介紹了numpy如何按條件給元素賦值np.where、np.clip問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06pandas之分組groupby()的使用整理與總結(jié)
這篇文章主要介紹了pandas之分組groupby()的使用整理與總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06解決Python3.7.0 SSL低版本導(dǎo)致Pip無法使用問題
這篇文章主要介紹了解決Python3.7.0 SSL低版本導(dǎo)致Pip無法使用問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09windows10 pycharm下安裝pyltp庫和加載模型實(shí)現(xiàn)語義角色標(biāo)注的示例代碼
這篇文章主要介紹了windows10 pycharm下安裝pyltp庫和加載模型實(shí)現(xiàn)語義角色標(biāo)注,本文通過圖文實(shí)例相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-05-05