Why am I getting name 'request' is not defined?



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.


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", {})

Answered By – Willem Van Onsem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More