简体   繁体   中英

How implement django.views.generic if earlier used request[Django]

How implement Django.views.generic if earlier used request?

    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

# Create your views here.
# New 
    
    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)

You can make ListView in following way:

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: Class based views requires their names to be written as model name as the prefix and actual view name as the suffix, so I changed it to BookListView from HomePage .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM