已登录,但无法从请求对象django

时间:2017-12-14 08:38:39

标签: python django django-views django-login

我正在尝试在类基本视图中访问django请求对象中的用户对象。但是,我收到错误:module 'django.http.request' has no attribute 'user'

以下是我的代码:

class FinanceHomePage(TemplateView):
template_name = 'finance/finance_homepage.html'

def get_context_data(self, **kwargs):
    context = super(FinanceHomePage, self).get_context_data(**kwargs)
    context['username'] = self.request.user.username 
    return context

只有登录后才能访问上述代码段。

**编辑** 以下是登录视图:

def user_login(request):

    if request.method == "POST":
       username = request.POST.get('username')
       password = request.POST.get('password')

       user = authenticate(username=username, password=password)

       if user:
           if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('homepage'))  # main page if login is successful

           else:
                return HttpResponse("ACCOUNT NOT ACTIVE")

        else:
            print('Someone tried to log in and failed')
            print('Username: {}, password, {}'.format(username, password))
            return HttpResponse('Invalid login details supplied')

    else:
        return render(request, 'authentication/login.html', {})

以下是我的self.request目录:

['COOKIES', 'FILES', 'GET', 'META', 'POST', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_cached_user', '_encoding', '_get_post', '_get_raw_host', '_get_scheme', '_initialize_handlers', '_load_post_and_files', '_mark_post_parse_error', '_messages', '_post_parse_error', '_read_started', '_set_post', '_stream', '_upload_handlers', 'body', 'build_absolute_uri', 'close', 'content_params', 'content_type', 'csrf_processing_done', 'encoding', 'environ', 'get_full_path', 'get_host', 'get_port', 'get_raw_uri', 'get_signed_cookie', 'is_ajax', 'is_secure', 'method', 'parse_file_upload', 'path', 'path_info', 'read', 'readline', 'readlines', 'resolver_match', 'scheme', 'session', 'upload_handlers', 'user', 'xreadlines']

以下是错误的完整堆栈跟踪:

Traceback:

File "/anaconda3/envs/MyLife/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/anaconda3/envs/MyLife/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "/anaconda3/envs/MyLife/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/anaconda3/envs/MyLife/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/anaconda3/envs/MyLife/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/anaconda3/envs/MyLife/lib/python3.6/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/anaconda3/envs/MyLife/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/anaconda3/envs/MyLife/lib/python3.6/site-packages/django/views/generic/base.py" in get
  155.         context = self.get_context_data(**kwargs)

File "/Users/kaijieang/Coding/MyLife/MyLife/finance/views/finance_index_view.py" in get_context_data
  10.         request.user.username

Exception Type: AttributeError at /finance/
Exception Value: module 'django.http.request' has no attribute 'user'

1 个答案:

答案 0 :(得分:1)

您在request(全局级别从django.http导入的模块)和self.request(视图实例的属性)之间感到困惑。虽然您的代码显示为self.request,但错误消息显示您最初使用的是request

您应该将其更改为self.request