i am working on a django project and struggling to understand class based views.
class readBooks(TemplateView):
template_name="books_read.html"
def get_context_data(self, **kwargs):
context = super(readBooks, self).get_context_data(**kwargs)
return context
def get_books(self):
wb=books.objects.all()
return wb
This is my class. Problem is using get_books function is not callable.how am i goin to call this function. sorry if i being too stupid asking. But i could not think of a better place than this. I also need to understand how am i goin to use the returned result of this function in the Html file.
I am very new to django and Django tutorial is not so helpful for me.Any help is highly appreciated.
You should use generic model interface of Class-Based Views
# Use this snippet to call Books.objects.all()
class ReadBooks(ListView):
template_name = "books_read.html"
model = Books
# if you want filter the Book model
class ReadBooks(ListView):
template_name = "books_read.html"
model = Books
def get_queryset(self, *args, **kwargs):
return self.model.objects.filter(author='someone')
that's the beauty of the Class-Based Views, if you just need the all records of books, the code below is enough but ig you want to more customization for the view like calling other model queries, then you should use get_context_data
class ReadBooks(ListView):
template_name = "books_read.html"
model = Books
def get_context_data(self, *args, **kwargs):
ctx = super(ReadBooks, self).get_context_data(*args, **kwargs)
ctx['authors'] = Author.objects.all()
return ctx
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.