Nice to meet you, everyone. I'm going to publish a memorandum of the process of creating a voting (poll) application using Django. Since I am a beginner of Qiita, please understand that some parts may be difficult to read.
series
-[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-No. 0- -[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 1- -[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 2-
View of MVC model is a program that returns the screen to be displayed to the user.
In the voting application, create the following four views:
Questions "Index" page --Show some of the latest questions Question "Details" page --Show question text and voting form without displaying results Question "Results" page --Display the results of a specific question Voting Page-Accepts specific question selections as votes
By the way, the Django feature that gets a view from a URL is called URLconf.
Implement the following operation using URLconf.
User accesses "/ polls / 100 /"
→ Read polls / urls.py to match path.'polls /'in config / urls.py
→ Returns details (request =
polls/views.py
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello,world.You're at the polls index.")
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
question_id = 100 is sandwiched between <> and captured from a part of the URL.
polls/urls.py
from django.urls import path
from . import views
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'),
]
Did you ever make something that didn't work ... It seems different. "Actually works" seems to mean "implement HttpRequest processing and exception handling to realize the behavior according to the actual operation".
Add the following to the view.
polls/views.py
from .models import Question
from django.template import loader
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))
Pass the latest_question_list to polls / index.html with "template.render (context, request)" and render it. It seems that Django's loader.get_template specification searches for rendering templates under the ".templates / app name (polls)" directory.
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 %}
You can also make a shortcut. Import render from django.shortcut.
polls/views.py
from .models import Question
from django.shortcuts import render
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {
'latest_question_list': latest_question_list,
}
return render(request, 'polls/index.html', context)
You should see a screen like this.
First, create a view.
polls/views.py
from django.http import HttpResponse, Http404
from .models import Question
from django.shortcuts import render
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question dose not exist")
return render(request, 'polls/detail.html', {'question': question})
Then HTML
polls/templates/polls/detail.html
{{question}}
Check the operation.
Since question_id = 5 exists, "http://127.0.0.1:8000/polls/5/" is displayed as follows. ..
Since question_id = 999 does not exist, "http://127.0.0.1:8000/polls/999/" is displayed as follows. .. Exception is caught and "Question dose not exist" is displayed.
Mark up the html on the detail page.
polls/templates/polls/detail.html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
"Http://127.0.0.1:8000/polls/5/" is displayed again.
Variableize the URL part. This is because the template needs to be modified when the URL is changed.
As a mechanism, you specified name ='detail' in polls / urls.py> urlpatterns> path. Load this in polls / templates / polls / index.html. Then the URL associated with name ='detail' will be read.
polls/templates/polls/index.html
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
polls/urls.py
urlpatterns = [
***
path('<int:question_id>/', views.detail, name='detail'),
***
]
There is no problem with the display.
The app I created this time is only one polls app. If you create multiple apps, they may have a detail view. To retrieve the detail view of the polls app, create and specify a namespace.
To create a namespace, add app_name =
polls/urls.py
app_name = 'polls'
urlpatterns = [
***
path('<int:question_id>/', views.detail, name='detail'),
***
]
The URL specification that specifies the namespace is
polls/templates/polls/index.html
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
That's all for today. Thank you very much.
Recommended Posts