最简单的CBV视图(不做赘述)

from django.views import View

class A(View):
    def get(self,request):
        return ....
    def post(self,request):
        return ....

# url.py:
path('login/',views.A.as_view()

 

高级类视图

ListView

from django.views.generic import ListView
from books.models import Publisher

class PublisherList(ListView):
   template_name = "t.html" # 默认是app名/publish_list model
= Publisher # 制定模型 context_object_name = 'my_favorite_publishers' # 默认是object_list # 这样在前端的模板中就可以for循环object_list

 

DetailView

from django.views.generic import DetailView
from books.models import Publisher, Book

class PublisherDetail(DetailView):
    model = Publisher
    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super().get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['book_list'] = Book.objects.all()
        return context
from django.views.generic import DetailView
from books.models import Publisher

class PublisherDetail(DetailView):

    context_object_name = 'publisher'
    queryset = Publisher.objects.all()
缩小遍历范围
class PublisherBookList(ListView):

    template_name = 'books/books_by_publisher.html'

    def get_queryset(self):
        self.publisher = get_object_or_404(Publisher, name=self.kwargs['publisher'])
        return Book.objects.filter(publisher=self.publisher)  # 这里还能有self.request
   def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super().get_context_data(**kwargs)
    # Add in the publisher
    context['publisher'] = self.publisher
    return context
动态查询
class AuthorDetailView(DetailView):

    queryset = Author.objects.all()

    def get_object(self):
        # Call the superclass
        object = super().get_object()
        # Record the last accessed date
        object.last_accessed = timezone.now()
        object.save()
        # Return the object
        return object
extra operation