BuilderBoba
BuilderBoba

Reputation: 23

Why does a function in views.py require a request parameter in this case in Django?

In url.py I have set up a new path within the main urlpatterns list:

path('ko/', views.ko),

I learned that I need to write this function in views.py to get the webpage going:

 def ko(request):
    return HttpResponse("It's a page")

My question is why doesn't the function work when I leave the parameter blank instead of request?:

def ko():
     return HttpResponse("It's a page")

Running the page when I delete the request parameter outputs a TypeError:ko() takes 0 positional arguments but 1 was given.

If I don't have a request input on the function call of views.ko then why is the request parameter necessary when writing the initial function, what is the request parameter doing, and where is this request parameter going into? What are its attributes? I would really appreciate a thorough response on its qualities.

Upvotes: 1

Views: 2268

Answers (2)

David
David

Reputation: 3

Each view function takes an HttpRequest object as its first parameter, which is typically named request

Upvotes: 0

user459872
user459872

Reputation: 24807

A view function, or view for short, is a Python function that takes a Web request and returns a Web response. So every view must accept an request parameter.

The request object contains metadata about the request, for example what HTTP request method used, The IP address of the client etc. You find the list of HttpRequest here

Also from the documentation.

Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view). The view gets passed the following arguments:

An instance of HttpRequest.

If the matched URL pattern contained no named groups, then the matches from the regular expression are provided as positional arguments.

The keyword arguments are made up of any named parts matched by the path expression that are provided, overridden by any arguments specified in the optional kwargs argument to django.urls.path() or django.urls.re_path().

Upvotes: 2

Related Questions