Finally, we will create a page using the template.
setting.py ######
TEMPLATE_DIRS = (
'path/to/your/templates' #It looks good anywhere
)
Of course, once you set it up, you have to prepare the place properly.
Once the template directory is ready, create more subdirectories for each app and create HTML templates in it. This time, create index.html in "polls".
index.html ######
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
HTML is coming in between Python programs. Is each process from {% hoge…%} to {% endhoge%}? There is a part surrounded by {{}} inside, but this may be something like echo in PHP. It seems that the value is returned to HTML as it is.
Once you have a template, set it as the view for that page.
views.py ######
from django.template import Context, loader
from polls.models import Poll
from django.http import HttpResponse
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
temp = loader.get_template('polls/index.html')
contxt = Context({
'latest_poll_list': latest_poll_list, #Show the latest one?
})
return HttpResponse(temp.render(contxt))
Also, if you use the shortcuts module, you can write it short as follows.
from django.shortcuts import render_to_response
#This eliminates the need for templates and http
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('polls/index.html',
{'latest_poll_list': latest_poll_list})
#Are you returning with the feeling that temp and contxt of the previous code are put together?
Personally, I prefer the previous writing style at the longest (because it is easy to understand). I want to use the shortcut after getting used to it.
*** By the way, there were two unsettling points, so I would like to mention them ***
’-pub_date’: What does the first hyphen mean?
[: 5]: Similarly, the colon is unclear.
Recommended Posts