📜  listview django - Python (1)

📅  最后修改于: 2023-12-03 15:17:24.642000             🧑  作者: Mango

ListView in Django - Introduction

In Django, the ListView Class-based View (CBV) is used to display a list of database objects on a web page.

How to use ListView in Django

Using ListView in Django is pretty straightforward. It requires defining a model to represent the object that needs to be displayed in the list view, creating a URL for the view, and defining a template to render the view.

Here's an example:

# urls.py
from django.urls import path
from .views import BookListView

urlpatterns = [
    path('books/', BookListView.as_view(), name='book-list'),
]

# views.py
from django.views.generic import ListView
from .models import Book

class BookListView(ListView):
    model = Book
    template_name = 'book_list.html'
    context_object_name = 'books'
    paginate_by = 10

# book_list.html
{% extends 'base.html' %}

{% block content %}
    <h1>Books</h1>
    <ul>
    {% for book in books %}
        <li>{{ book.title }}</li>
    {% endfor %}
    </ul>
{% endblock %}

In this example, we create a list view of Book objects. The Book model is defined in models.py and is imported in views.py. The BookListView is a subclass of ListView that inherits various methods and properties from the parent class.

The model property is used to specify the model that the view will use to retrieve the data. The template_name property specifies the name of the template that will be used to render the data. The context_object_name property sets the name of the context variable that the list of objects will be assigned to. The paginate_by property sets the number of items to display per page.

Finally, we create a template book_list.html that extends base.html and renders the list of books using a for loop.

Conclusion

Using the ListView Class-based View is a powerful and simple way of displaying lists of database objects. It reduces the amount of boilerplate code you need to write and makes it easier to create scalable and maintainable web applications.