簡體   English   中英

如何在DJANGO中使用基於類的視圖調用函數並在ui上獲得結果

[英]how to call the function and get the result on ui using class based views IN DJANGO

我正在研究一個django項目,並努力理解基於類的視圖。

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

這是我的班級。 問題是使用get_books函數是不可調用的。我是否會調用此函數。 對不起,如果我太傻了問。 但我想不出比這更好的地方。 我還需要了解如何在Html文件中使用此函數的返回結果。

我是django的新手,Django教程對我沒那么有用。非常感謝任何幫助。

您應該使用基於類的視圖的通用模型接口

# 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')

這就是基於類的視圖的美妙之處,如果您只需要書籍的所有記錄,下面的代碼就足夠了,但是您想要更多地自定義視圖,比如調用其他模型查詢,那么您應該使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM