[PYTHON] Django tutorial summary for beginners by beginners ③ (View)

Introduction

This article is a series of steps through Django's official tutorials. This time, we will proceed with the third article, "Creating your first Django app, part 3."

Summary of Django tutorials for beginners by beginners ① (project creation ~) Django tutorial summary for beginners by beginners ② (Model, Admin) Django tutorial summary for beginners by beginners ③ (View) Django tutorial summary for beginners by beginners ④ (Generic View) Django tutorial summary for beginners by beginners ⑤ (test) Django tutorial summary for beginners by beginners ⑥ (static file) Summary of Django tutorials for beginners by beginners ⑦ (Customize Admin)

Creating your first Django app, part 3

https://docs.djangoproject.com/ja/3.0/intro/tutorial03/

Write more views

Add to polls / views.py.

polls/views.py


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)

Add it to polls / urls.py as well.

polls/urls.py


from django.urls import path

from . import views

urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
    # ex: /polls/5/
    path('<int:question_id>/', views.detail, name='detail'),
    # ex: /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

This sequence of steps is similar to routing work such as Rails.

Write a view that actually works

polls/views.py


from django.http import HttpResponse

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

# Leave the rest of the views (detail, results, vote) unchanged

This is working, but I'll change it to use the Html template like Rails.

Inside the polls directory, create a templates / polls directory.

Create templeteʻindex.html for index.

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 %}

Also, the index of view will be changed accordingly.

polls/views.py


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

Shortcut: render ()

polls/views.py


from django.shortcuts import render

from .models import Question


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)

The flow of rendering the series of Templete mentioned above is often used, so it can be omitted in this way.

Sending a 404 error

Change detail to give an error when there is no question with the requested question ID.

polls/views.py


from django.http import Http404
from django.shortcuts import render

from .models import Question
# ...
def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})

Shortcut: get_object_or_404 ()

polls/views.py


from django.shortcuts import get_object_or_404, render

from .models import Question
# ...
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

Shortcuts are provided because the process of wearing an Http404 when the previous object does not exist is also often used.

There is also a similar shortcut called get_list_or_404 (). This function behaves like get_object_or_404 (), but throws an Http404 if the list is empty.

Use template system

Create a templete corresponding to the detail above.

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>

Remove hardcoded URL in template

Some of the links were hard coated in polls / index.html. Since the name argument was specified in the path function in polls.urls, replace it there.

This makes it easy to change links when they change.

polls/index.html


- <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
+ <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

(Remove-, add +)

URL namespace

Currently only the polls app exists, but what if there are other apps and the same url name argument is taken there?

In this case, add ʻapp_name to polls / urls.py`.

polls/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'),
]

polls / index.html will change accordingly.

polls/templates/polls/index.html


- <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
+ <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

Recommended Posts

Django tutorial summary for beginners by beginners ③ (View)
Django tutorial summary for beginners by beginners ④ (Generic View)
Django tutorial summary for beginners by beginners ⑤ (test)
Django tutorial summary for beginners by beginners ⑦ (Customize Admin)
Django tutorial summary for beginners by beginners ⑥ (static file)
Django Tutorial Summary for Beginners by Beginners (Model, Admin)
Django tutorial summary for beginners by beginners ① (project creation ~)
Python Django tutorial summary
Reference resource summary (for beginners)
[Explanation for beginners] TensorFlow tutorial MNIST (for beginners)
Machine learning summary by Python beginners
[For beginners] Django -Development environment construction-
What is scraping? [Summary for beginners]
TensorFlow Tutorial MNIST For ML Beginners
Django Girls Tutorial Summary First Half
Pandas basics summary link for beginners
[Deprecated] Chainer v1.24.0 Tutorial for beginners
TensorFlow Tutorial -MNIST For ML Beginners
Django Summary
Django Summary
[Linux command summary] Command list [Must-see for beginners]
Linux operation for beginners Basic command summary
A textbook for beginners made by Python beginners
An introduction to object-oriented programming for beginners by beginners
Roadmap for beginners
Django function-based view
Python Django Tutorial (5)
Python Django Tutorial (2)
Python tutorial summary
django tutorial memo
Python Django Tutorial (8)
Python Django Tutorial (6)
Start Django Tutorial 1
About Nim higher-order functions for Nim beginners written by Nim beginners
Django class-based view
Django filter summary
Conducting the TensorFlow MNIST For ML Beginners Tutorial
Python Django Tutorial (7)
Python Django Tutorial (1)
Python Django tutorial tutorial
Python Django Tutorial (3)
Python Django Tutorial (4)
[Translation] NumPy Official Tutorial "NumPy: the absolute basics for beginners"
I tried the MNIST tutorial for beginners of tensorflow.
Summary of pre-processing practices for Python beginners (Pandas dataframe)
[Linux] Basics of authority setting by chmod for beginners
[For beginners] Django Frequently used commands and reference collection
Machine learning tutorial summary
Spacemacs settings (for beginners)
Django Polymorphic Associations Tutorial
python textbook for beginners
Faker summary by language
Django2 View configuration pattern
Django Girls Tutorial Note
Dijkstra algorithm for beginners
Summary for learning RAPIDS
Batch thought by beginners
OpenCV for Python beginners
[For beginners] Basics of Python explained by Java Gold Part 2
[Roughly translate TensorFlow Tutorial into Japanese] 1. MNIST For ML Beginners
[For beginners] Summary of standard input in Python (with explanation)