Django学习笔记3

From the last two parts, we know, by using the HttpResponse we can return text to the web page, and by using admin site we can edit our question. Then we have to show our polls on the page. We are going to show latest 5 questions link. We can click it to see the details.

1.Showing the question link

Work with views.py index function. We only need an argument, request from the server. Then call the Question model and visit the latest five question by coding Question.objects.order_by('-pub_time')[:5]. Of course we can code the display lines in it. But it will be troublesome when we have a lot to write and edit. So why not write it in the html file to make the structure more clearly. So now let's create a templates directory in the app polls and subdirectory polls to contain the html files.Why not directly put the html files in the templates? I'm not satisfied with the answer. But from my understanding, the program will traverse the INSTALLED_APPS and look into the templates. It will go into the first one that matches the html name. So we need one subdirectory with the app name to differentiate the html files with the same name in different apps. Create templates->polls->index.html, detail.html.

But how do we correspond the templates with views.py function. In the views.py index function, we load the designated templates html file, pass a context which is a dictionary form to deliver arguments, render it, namely to process it and make it in a state and return the HttpResponse rendered result. But we can just return the render() shortcut to tackle all of them. Amazing render!!!

next version:

next version:

Here comes the html edition. But it has a shortcome that the url is hardcoded. Recall the url path we wrote before, path('<int:question_id>/', views.detail, name='detail'), the name is nickname of the path, so that we can use the nickname which will be easier for us to change another path in the future.

next version:

 next version: to differentiate the same url name in different apps, we can write app_name = 'polls' in polls/urls.py top of the INSTALLED_APPS.

2. showing the choice.

We've writtern the url link to the detail of the question. So go to the detail funtion in views.py and deliver the question to the html file, meanwhile an exception is necessary to takcle the problem of question=none. And we code the question and choices display lines in detail.html.

next version:

猜你喜欢

转载自www.cnblogs.com/nokiyaya/p/12336911.html