开发者

Django NameError: name 'request' is not defined

开发者 https://www.devze.com 2023-03-29 21:10 出处:网络
I have imported these modules: from django.http import HttpResponseRedirect from django.shortcuts import render_to_response

I have imported these modules:

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

and then I try to c开发者_JAVA百科all a class like so:

sh = MyClass(request.FILES['img'])
sh.read_image()

but it throws error "NameError: name 'request' is not defined", but I don't get it why, because I have imported necessary modules.


Where are you making your class? If you want access to a request, you usually have to be inside a view, like so:

def my_view(request):
    sh = MyClass(request.FILES['img'])
    sh.read_image()
    return render_to_response('template.html')


Neither of those import statements use the name 'request', so you can't be importing that name.

In any case, the request isn't something you import, it's something that's passed to each view. If your code is outside the view, you need to pass the request to it.

0

精彩评论

暂无评论...
验证码 换一张
取 消