Django application templates
Description
Render the application specific html via View
Create the templates dir
dj-env) [dj_adm@localhost polls]$ mkdir templates
(dj-env) [dj_adm@localhost polls]$ mkdir -p templates/polls/
(dj-env) [dj_adm@localhost polls]$ tree
.
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│ ├── 0001_initial.py
│ ├── __init__.py
│ └── __pycache__
│ ├── 0001_initial.cpython-39.pyc
│ └── __init__.cpython-39.pyc
├── models.py
├── __pycache__
│ ├── admin.cpython-39.pyc
│ ├── apps.cpython-39.pyc
│ ├── __init__.cpython-39.pyc
│ ├── models.cpython-39.pyc
│ ├── urls.cpython-39.pyc
│ └── views.cpython-39.pyc
├── templates
│ └── polls
├── tests.py
├── urls.py
└── views.py
5 directories, 17 files
In settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Your project’s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the INSTALLED_APPS.
Index View
from django.http import HttpResponse, Http404
from django.template import loader
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
# output = ', '.join([q.question_text for q in latest_question_list])
# return HttpResponse("Hello, world. You're at the polls index.")
template = loader.get_template('polls/index.html')
context = {
'latest_question_list' : latest_question_list
}
return HttpResponse(template.render(context, request))
Urls.py
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Polls</title>
</head>
<body>
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>
<!-- <a href="/polls/{{ question.id }}/">{{ question.question_text }}</a> -->
<a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>
Comments
Post a Comment