2017-08-07 40 views
1

使用視圖變量在view.py:不能在模板

class DisplayView(generic.ListView): 
    def get(self, request, **kwargs): 
     if request.method == "GET": 
      selection = request.GET.getlist("selection") # list of checkbox values with name 'selection 
      articles = Article.objects.all() 

      args = {'articles': articles, 'selection': selection} 
      print(selection) 
      print(articles) 
      return render(request, 'display.html', args) 

在display.html:

{% extends 'myapp/base.html' %} 

{%block contentblock %} 

{% for section in selection %} 
    <h1>{{ section }}</h1> 
     <script language="javascript">console.log(selection)</script> 
{% endfor %} 

{% endblock %} 

我可以在我的終端 '選擇' 和 '文章' 印上看到,這意味着視圖正確地從複選框中獲取數據。 但是,我的html中沒有任何內容出現,並且console.log引發錯誤,表示數據未傳遞給模板... 爲什麼?

回答

0

首先,您應該爲選擇部分添加{%endfor%},以及使用兩個for循環。其次,你需要添加'到模板名稱回報呈現

+0

是的,對不起,他們只是複製粘貼錯誤,我在這裏簡單的代碼。在我的原始代碼中,沒有這樣的錯誤。這不是問題。 – ben

3

爲腳本,你需要加上括號:

<script language="javascript">console.log({{ selection }})</script> 
1

改變這一行

return render(request, display.html, args) 

return render(request, 'display.html', args) 

記住html正好在模板內而不在其他任何子文件夾內,如果子文件夾在那裏添加文件夾名稱be前面這裏面單引號

,並在模板

{% extends 'myapp/base.html' %} 

{% block contentblock %} 
<script language="javascript">console.log({{ selection }})</script> 
    {% for section in selection %} 
     <h1>{{ section }}</h1> 
      <script language="javascript">console.log({{ articles }})</script> 
     {% for article in articles %} 
      <h2>{{ article }}<h2> 
     {% endfor %} 
    {% endfor %} 

    {% endblock %}