The django.urls.reverse
method that first appeared in Django Tutorial part4 (ver2.2). (Last line below)
polls/views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from .models import Choice, Question
# ...
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
The last line reverse ('polls: results', args = (question.id,))
will be linked to the 4th line of view.py
below to generate a redirect URL and return it to the client. I understand that, but ...
polls/urls.py
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")
]
** Why reverse? What are you doing "reverse"? Is something upside down? ** ** ** What is the "order" that is not the "reverse"? ** **
The question came up and this code didn't come into my head. That is the beginning.
Because, if it is Flask that I touched until just before, I can write it like redirect (url_for ('polls.results'))
and generate a URL to results, it is easy to understand intuitively as it is read. So even more so, "Why is Django reverse here?"
At first glance, I found two links that looked like it, so I took a quick look at these two.
However, django.urls utility functions says "Oh, that's reverse / reverse?" In the method definition. ..
After reading URL Dispatcher, I can imagine it.
Django provides a solution such that the URL mapper is the only repository of the URL design. You feed it with your URLconf and then it can be used in both directions:
The first one is the usage we’ve been discussing in the previous sections. The second one is what is known as reverse resolution of URLs, reverse URL matching, reverse URL lookup, or simply URL reversing.
From the bold part of the above quote
--User to server request = Find the corresponding view based on the URL = ʻURL-> view= This is the "order" --Find the corresponding URL based on view =
view-> URL` = This is" reverse "
I found out that.
To be honest, I was confused without being aware of the concept of forward / reverse lookup between URL and view. I feel like I got a glimpse of the Explicit is better spirit of Python.
Recommended Posts