2016-04-15 66 views
-3

我想從django數據庫檢索多個記錄以顯示在網頁上的表格中。檢索多個項目並在網站上顯示它們

這是到目前爲止我的代碼...

class AdminView(TemplateView): 
template_name = 'admin.html' 
print("hello world") 
def get(self, request): 
    template = 'admin.html' 
    data = str(Quiz.objects.all()) 
    admin = AdminForm(request.GET) 
    context = {"admin": admin} 
    context['data'] = data 
    return render(request, template, context) 

這是網頁那麼遠,

{% if request.user.is_authenticated%} 
{% if request.user.username == "teacher" %} 
    <!DOCTYPE html> 
    <html lang="en"> 
    <head> 
     {% load staticfiles %} 
     <meta charset="UTF-8"> 
     <title>Admin</title> 
     <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" /> 
    </head> 
    <body> 
    {% include 'navbar.html' %} 

    Admin Test 

    {{ data }} 

    </body> 
    </html> 
    {% endif %} 
{% endif %} 

{% if not request.user.is_authenticated %} 
<h2>Login Required</h2> 
{% endif %} 

你覺得有什麼不對的代碼?我怎樣才能讓它顯示str?

+0

*是什麼*不對的代碼? – Sayse

+0

這段代碼究竟有什麼問題。 –

+0

[so]是爲了幫助解決問題,而不是猜測它們是什麼,你應該描述你正試圖解決的問題。 – Sayse

回答

1

對於你正在試圖獲得一個查詢集的字符串表示

data = str(Quiz.objects.all()) 

你不需要,只需設置數據的查詢集

data = Quiz.objects.all() 

然後,只需重複一些奇怪的原因在他們身上

{% for obj in data %} 
    {{ obj }} 
{% endfor %} 
+0

這仍然只是輸出: 管理員測試測驗對象測驗對象測驗對象測驗對象測驗對象測驗對象測驗對象測驗對象測驗對象測驗對象測驗對象測驗對象 - 到網頁。 –

+0

@PhilipCrocker - 是的,這裏的'obj'是你的測驗對象的一個​​實例,所以你需要決定你想要顯示哪個對象的部分 – Sayse

+0

這就是這個代碼輸出的內容。我應該使用什麼語法來顯示對象的特定部分。 –

1

要增加sayse回答你可以,例如,做類似:

{% for obj in data %} 
    {{ obj.display }} 
{% endfor %} 

你的測驗模型可能是這樣的:

class Quiz(models.Model): 

    ... 

    def display(self): 
     return 'This will display on your page' 
相關問題