嗨,我正在研究python-django(v1.6)项目,我需要拿出一张表,其中包含我数据库中的数据。我已经准备好了Templeteview和模板。
我的看法
class MyView(TemplateView):
model = Mymodel
template_name = "home.html"
def get_context_data(self, *args, **kwargs):
context = super(MyView, self).get_context_data(*args, **kwargs)
context['ngapp'] = "Myapp"
return context
def get_data(request):
query_results = Mymodel.objects.objects.all()
我的HTML
{% extends "base.html" %}
<!--Page heading-->
{% block page_title %}My home{% endblock %}
<!---->
{% block content %}
<div>
<table class="table">
<tr>
<th>Name</th>
</tr>
{% for item in query_results %}
<tr>
<td> {{ item.name}}</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
根据我的代码,不知道为什么不显示名称。如何从数据库中获取数据(特定列)并将其显示在表中?使用AngularJS更好的方法?在此先感谢大家
最佳答案
您没有将查询集传递给模板。尝试这样:
class MyView(TemplateView):
model = Mymodel
template_name = "home.html"
def get_context_data(self, *args, **kwargs):
context = super(MyView, self).get_context_data(*args, **kwargs)
context['ngapp'] = "Myapp"
context['query_results'] = self.get_data()
return context
def get_data(self):
query_results = self.model.objects.all()
return query_results