Django2.2.1使用template显示MySQL数据库信息
定义模板
在polls/路径下新建文件夹templates
然后在templates文件夹下新建文件夹polls
原因:Django只会匹配第一个同名模板,如果不在templates文件夹下新建polls文件夹的话,在多个应用中存在同名模板时,会弄错。
综上,在“项目路径/polls/templates/polls”路径下新建模板文件index.html
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
定义视图函数
在polls应用的views.py文件中定义对应的视图函数,用于response index.html到前端
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
修改polls的urls.py
urlpatterns = [
...
path('', views.index, name='index'),
]