[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 3-

Introduction

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-

Start work

Overview

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.

Write more views

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 = , question_id = 100) of views.py because it matches path.'100 /'of polls / urls.py

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

Write a view that actually works

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. image.png image.png

Sending a 404 error

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. .. image.png

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. image.png

Use template system

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. image.png

Remove hardcoded URL in template

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.

image.png

URL name namespace

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 = to /templates/ /index.html.

polls/urls.py


app_name = 'polls'
urlpatterns = [
    ***
    path('<int:question_id>/', views.detail, name='detail'),
    ***
]

The URL specification that specifies the namespace is : detail.

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

[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 7-
[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-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 0-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 6-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 4-
[Beginner] [Python / Django] A fledgling web engineer tried a Django tutorial-Part 3-
Django python web framework
Deploy a Python 3.6 / Django / Postgres web app on Azure
(Python) Try to develop a web application using Django
CTF beginner tried to build a problem server (web) [Problem]
Web scraping beginner with python
[Django3] Display a web page in Django3 + WSL + Python virtual environment
A liberal arts engineer tried knocking 100 language processes in Python 02
A python beginner tried to intern at an IT company
A liberal arts engineer tried knocking 100 language processes in Python 01
A liberal arts engineer tried knocking 100 language processes in Python 00
If you know Python, you can make a web application with Django
[Python / Django] Create a web API that responds in JSON format
I tried web scraping with python.
Python beginner tried 100 language processing knock 2015 (05 ~ 09)
web coder tried excel in Python
When a Python beginner tried using Bottle, it worked unexpectedly easily.
Python beginner tried 100 language processing knock 2015 (00 ~ 04)
A beginner of machine learning tried to predict Arima Kinen with python
An introduction to self-made Python web applications for a sluggish third-year web engineer
A note where a Python beginner got stuck
[Beginner] Python web scraping using Google Colaboratory
[Python] A quick web application with Bottle!
I tried to make a Web API
Use Django from a local Python script
Run a Python web application with Docker
Let's make a web framework with Python! (1)
I tried benchmarking a web application framework
Let's make a web framework with Python! (2)
I made a WEB application with Django
A python beginner tried to intern at an IT company [Day 2 chatbot survey]
A python beginner tried to intern at an IT company [Day 1 development process]
Go beginner tried to create a cloud native web application using Datastore / GAE
[ES Lab] I tried to develop a WEB application with Python and Flask ②
I searched for the skills needed to become a web engineer in Python
Machine learning memo of a fledgling engineer Part 1
2-2. Input for becoming a WEB engineer (Linux basics)
I tried web scraping using python and selenium
I tried playing a typing game in Python
[Python] Build a Django development environment with Docker
[Memo] I tried a pivot table in Python
[Python] Draw a Mickey Mouse with Turtle [Beginner]
Create a web map using Python and GDAL
Steps to develop a web application in Python
[Python] Web development preparation (building a virtual environment)
I tried reading a CSV file using Python
Programming beginner Python3 engineer certification basic exam record
Launch a web server with Python and Flask
Machine learning memo of a fledgling engineer Part 2
Run a Python file from html using Django
I tried running alembic, a Python migration tool
Quickly build a Python Django environment with IntelliJ
A memo for creating a python environment by a beginner
[Python] Beginners troubleshoot while studying Django web applications
To myself as a Django beginner (3)-Hello world! ---