Python Django 通用视图和错误视图的使用

发布时间 2023-04-11 09:03:04作者: 幻非

定义通用视图

修改 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="联系方式")
    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 的函数

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.pyurlpatterns 列表中新建一个路由

path('author/', views.AuthorListView.as_view())

image

新建一个 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 文件内的 urlpatterns 列表中是否含有 book 的路由

image

如果为无报错且为空白页面,请注意查看数据库内是否含有数据,下面为添加示例数据的代码

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');

可在此处执行

image

如无问题,将会看到作者信息

image

定义错误视图模板

修改 chapter1/settings.py 文件

DEBUG = False

ALLOWED_HOSTS = ['*']

image

新增 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>

此时进入未定义的路由网址时,便会显示上面编写的网页

image