Home > Article > Backend Development > How to use Python Django's generic views and error views?
Modify the AuthorInfo
class in the book/models.py
code. If it is consistent, there is no need to modify it
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="联系方式") age = models.IntegerField(verbose_name="年龄", default=30) sex = models.CharField(max_length=2, verbose_name="性别", default="男") def __str__(self): return self.name
inbook/views.py
Create a new AuthorListView
function under the file
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"## in
book/urls.py The
urlpatterns Create a new route in the list
path('author/', views.AuthorListView.as_view())New
templates/list.html File
<!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>Access http://127.0.0.1:8000/book/authorlist/If you cannot access the page, please check the
urlpatterns list in the
chapter1/urls.py file Does it contain the route of
book
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');can be executed here If there is no problem, you will see the author information
Define error view templateModify
chapter1/settings.py File
DEBUG = False ALLOWED_HOSTS = ['*']New
templates/404 .html file
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>此页面未找到</title> </head> <body> <h3>自定义的404页面</h3> <p>您访问的页面不存在</p> </body> </html>When entering the undefined routing URL, the webpage written above will be displayed
The above is the detailed content of How to use Python Django's generic views and error views?. For more information, please follow other related articles on the PHP Chinese website!