Fayzulla
Fayzulla

Reputation: 69

Understanding the "args" of HttpResponseRedirect in views.pyfile in Django

I have these two functions in my views.py file:

def entry(request, title):
    if title not in util.list_entries():
        return render(request, "encyclopedia/error.html", {
            "error": "Page Not Found",
            "query": title
        })
    else:
        return render(request, "encyclopedia/entry.html", {
            "entry": markdown2.markdown(util.get_entry(title)),
            "title": title
        })


def search(request):
    if request.POST["q"] in util.list_entries():
        return HttpResponseRedirect(reverse("entry", args=(request.POST["q"],)))
    else:
        return render(request, "encyclopedia/error.html")

How we can understand the args of HttpResponseRedirect. Where this args passed in the entry function? I just need the behind the scene action of this "args".

Upvotes: 1

Views: 551

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

The url pattern has likely a parameter, for example:

path('entry/<str:item>/', some_view, name='entry'),

by using the args=… and kwargs=… parameters of the reverse(…) function [Django-doc], you fill in the values for the parameter.

args expects an iterable of items, these are positional parameters. The kwargs expect a dictionary that maps strings to values, these are the named parameters.

With the given example for the entry path, if the request has a POST value foobar, it will thus construct a url /entry/foobar/.

It is however more convenient to use redirect(…) [Django-doc]. This basically calls the reverse, and then wraps the result in a HttpResponseRedirect, but it uses itself positional and named parameters to fill in the values:

from django.shortcuts import redirect

def search(request):
    q = request.POST.get('q')
    if q in util.list_entries():
        return redirect('entry', q)
    else:
        return render(request, 'encyclopedia/error.html')

Upvotes: 2

Related Questions