Home  >  Article  >  Backend Development  >  How to use Python Django's generic views and error views?

How to use Python Django's generic views and error views?

WBOY
WBOYforward
2023-05-08 21:49:071054browse

Define the general view

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"

How to use Python Djangos generic views and error views?

## in

book/urls.py The urlpatterns Create a new route in the list

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

How to use Python Djangos generic views and error views?

New

templates/list.html File




    
    
    Document

    {% for item in my_author %}
  • {{ item.name }}
  • {% endfor %}

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

How to use Python Djangos generic views and error views?

If there is no error and the page is blank, please check whether the database contains data. The following is how to add sample data Code

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

How to use Python Djangos generic views and error views?

If there is no problem, you will see the author information

How to use Python Djangos generic views and error views?

Define error view template

Modify

chapter1/settings.py File

DEBUG = False

ALLOWED_HOSTS = ['*']

How to use Python Djangos generic views and error views?

New

templates/404 .html file




    
    
    此页面未找到

自定义的404页面

您访问的页面不存在

When entering the undefined routing URL, the webpage written above will be displayed

How to use Python Djangos generic views and error views?

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete