1, django dynamic templates, data is always ready to function by the views and specify rendered on a template html page; function is responsible for data views, html page is responsible for the presentation style.
2, written views function
from django.shortcuts import render from django.shortcuts import HttpResponse from .models import CnbTitle # 编写一个函数,显示所有的CnbTitle def show_all_cnbtitle(request): all_cnbtitle = CnbTitle.objects.order_by('date_add') context = {'all_cnbtitle': all_cnbtitle} return render(request, 'all_cnbtitle.html', context)
First: views.py in the introduction of new models, is CnbTitle class;
admin background operation, in fact, is the addition of one CnbTitle object class, CnbTitle.objects.order_by represents removed from the database all CnbTitle object classes, and they are arranged in ascending order of time;
all_cnbtitle is a collection, for receiving all the objects.
Finally, as usual, it will be packaged as a parameter a dictionary, passed to go as a template context. Note that this wording, template rendering vast majority of arguments are true.
3, writing template
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>All CnbTitle</title> </head> <body> <h1>列举所有文章标题:</h1> {% for title in all_cnbtitle %} <h3>标题:{{title.text}}</h3> <p>添加时间:{{title.date_add}}</p> <br /><br /> {% endfor %} </body> </html>
Between the template <body> </ body>, is not an ordinary html tags, but django template tags.
The contents of these elements certainly not the final will be displayed on the page, at first glance, this looks like a for loop, and the fact that it really is really a for loop:
%}% {Put inside python code to accomplish a specific function or effect;
{{}} Is variable;
{##} is a comment.
When this template is opened, will attempt to remove the elements from the variable all_cnbtitle sequentially transmitted, then the element attribute points out, on <h3> </ h3> and <p> </ p> where each display element is placed 2 wrap, in order to distinguish one element and the next.
4, write url
from django.urls import path from . import views urlpatterns = [ path('first_page/', views.first_page, name='first_page'), path('first_temp/', views.first_temp, name='first_temp'), path('show_all_cnbtitle/', views.show_all_cnbtitle, name='show_all_cnbtitle'), ]
5, enter the address: http: //127.0.0.1: 8000 / test_app / show_all_cnbtitle /
Access effect is as follows: