Как реализовать django.views.generic, если ранее использовался request[Django]

Как реализовать Django.views.generic, если ранее использовался запрос?

    from django.shortcuts import render,redirect
    from django.http import HttpResponse
    from .models import *
    from django.contrib.auth import login,logout,authenticate
    from .forms import *
    from django.views.generic import ListView

Создайте свои представления здесь.

Новый

    
    class HomePage(ListView):
        model = Book
        template_name = 'book/templates/home.html'

Old

    def home(request):
        books=Book.objects.all()
        context={'books':books}
        if request.user.is_staff:
            return render(request,'book/templates/adminhome.html',context)
        else:    
            return render(request,'book/templates/home.html',context)

Вы можете сделать ListView следующим образом:

class BookListView(ListView):
    model=Book
    context_object_name='books'
    
    def get_template_names(self):
        if self.request.user.is_staff:
            return ['book/templates/adminhome.html']
        else:
            return ['book/templates/home.html']

Note: Представления на основе классов требуют, чтобы их имена записывались как имя модели в качестве префикса и фактическое имя представления в качестве суффикса, поэтому я изменил его на BookListView из HomePage.

Вернуться на верх