The basic knowledge points are all finished. Next, complete the sample project Li
The code needed now includes three aspects, which are in no order.
- 1. Define view
- 2. Define URLconf
- 3. Define template
Definition view
Write the file booktest/views.py as follows:
from django.shortcuts import render from booktest.models import BookInfo #Home page, showing all books def index(reqeust): #Search all books booklist = BookInfo.objects.all() #Pass the book list to the template and render the template return render(reqeust, 'booktest/index.html', {'booklist': booklist}) #Detailed page, receive the number of the book, query according to the number, find all the heroes of the book through the relationship and display def detail(reqeust, bid): #Corresponding books according to book number book = BookInfo.objects.get(id=int(bid)) #Find all hero information in the book heros = book.heroinfo_set.all() #Pass the book information to the template, and then render the template return render(reqeust, 'booktest/detail.html', {'book':book,'heros':heros})
Defining URLconf
Write the file booktest/urls.py as follows:
from django.conf.urls import url #Import view module from booktest import views urlpatterns = [ #Configure homepage url url(r'^$', views.index), #Configure the detailed page url, d + represents multiple numbers, parentheses are used for values, it is recommended to review the regular expressions url(r'^(\d+)/$',views.detail), ]
Defining templates
Write templates/booktest/index.html file as follows:
<html> <head> <title>home page</title> </head> <body> <h1>List of books</h1> <ul> {#Traverse book list#} {%for book in booklist%} <li> {#Output the book name and set the hyperlink. The link address is a number#} <a href="/{{book.id}}/">{{book.btitle}}</a> </li> {%endfor%} </ul> </body> </html>
Write templates/booktest/detail.html file as follows:
<html> <head> <title>Detailed page</title> </head> <body> {#Output book title#} <h1>{{book.btitle}}</h1> <ul> {#Find all the heroes of the book through relationships and traverse#} {%for hero in heros%} {#Output hero's name and description#} <li>{{hero.hname}}---{{hero.hcomment}}</li> {%endfor%} </ul> </body> </html>
summary
- Install and configure django running environment
- Write the model and use the API to interact with the database
- Managing data in the background with django
- Receive the request through the view and obtain the data through the model
- Call template to complete presentation