Home > Blockchain >  Why am I getting name 'request' is not defined?
Why am I getting name 'request' is not defined?

Time:11-15

I'm following a Django tutorial and have reached the point of using return renderand currently my views.py looks like this:

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def construction_view(*args, **kwargs):
    return HttpResponse("<h1> This site is currently being constructed. Please check back later </h1>")

def home_view(*args, **kwargs):
    return render(request, "home.html", {})

I am getting an error whien trying to go to my home page:

views.py", line 9, in home_view
    return render(request, "home.html", {})
NameError: name 'request' is not defined

Not sure what is causing this as according to Django docs request is part of render which is imported above.

CodePudding user response:

request is always the first parameter of any view. In your view, your function only has *args and **kwargs, so request will be the first item in the args. It is better to make the request parameter explicit and work with:

#        request ↓
def home_view(request, *args, **kwargs):
    return render(request, "home.html", {})

Since you likely only use this view for URL patterns without URL patterns, you can probably omit the *args and **kwargs:

#                  ↓ omit *args and **kwargs
def home_view(request):
    return render(request, "home.html", {})
  • Related