Tech C**P
14 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
Here we aim to design templates and render them to interact with Django the way it likes! We try to isolate the page's design.

Create a folder called templates in polls directory (this is the default folder name where django will look for app templates). Inside of templates create polls directory and inside of it create index.html file. So your templates are in path polls/templates/polls/index.html.

We have polls inside of templates folder to render templates in the format of loader.get_template('polls/index.html').

NOTE: if you don't create polls subdirectory inside of templates and you have templates we the same name in different apps (in the same project) you would encounter bizarre problems. DON'T DO THAT! (Django will choose the first template it finds whose name matches)

Now put the below code in 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 %}


OK now do as follow in index function in polls/views.py for template rendering:
from django.http import HttpResponse
from django.template import loader
from .models import Question


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))


Note that we have imported loader from django.template.

As you can see above, we have rendered the template with our variables (context) and passed it to http response object. We have used django.template module to render templates.

I've got the below result (next picture) what about you?

#django #loader #render #templates #django_part10