Reputation: 5618
Can someone please explain what is going on here with the Django Tutorial Part 4
Specifically, how the map function is working?
I understand that URLs shouldn't be hardcoded in the view functions.
return HttpResponseRedirect(reverse('mysite.polls.views.results', args=(p.id,)))
Upvotes: 4
Views: 7978
Reputation: 376052
The reverse
function has access to the URL map that Django uses to find a view function for incoming URLs. In this case, you pass in a view function, and the arguments it will get, and it finds the URL that would map to it. Then the HttpResponseRedirect function creates a response that directs the browser to visit that URL.
This is a way of saying, "Now call the mysite.polls.views.results view."
Upvotes: 7
Reputation: 25164
When defining URLs in Django you have the option of specifying a name to your URL: url(regex, view, kwargs=None, name=None, prefix='') such as what they do in the tutorial naming it poll_results
:
url(r'^(?P<object_id>\d+)/results/$',
'django.views.generic.list_detail.object_detail',
dict(info_dict, template_name='polls/results.html'), 'poll_results'),
This pattern has one named group: object_id
. The reverse function looks up the URL pattern named poll_results
and passes p.id
to be used for object_id
in the URL pattern. The function returns the URL built from the regex and the passed parameters.
Upvotes: 1