此代码有什么问题,它将产生以下错误:
> 'SessionStore' object has no attribute 'GET'
这是代码:
def blog_detail(request, blog_slug):
blog = get_object_or_404(Blog, slug=blog_slug)
session_key = 'blog_views_{}'.format(blog.slug)
if not request.session.GET.get('session_key', False)
blog.blog_views += 1
blog.save()
request.session['session_key'] = True
return render(request, 'blogs/blog-detail.html', {'blog':blog})
我认为使用request.session
做错了。谢谢。您能帮我吗?
编辑:追溯
Environment:
Request Method: GET
Request URL: http://localhost:8000/dramatically-productivate-global-functionalities-whereas-reliable-internal-or-organic-sources
Django Version: 2.2.1
Python Version: 3.7.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blogs',
'users',
'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "E:\Practice\new-blog\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "E:\Practice\new-blog\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "E:\Practice\new-blog\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\Practice\new-blog\src\blogs\views.py" in blog_detail
53. if not request.session.GET.get('session_key', False):
Exception Type: AttributeError at /dramatically-productivate-global-functionalities-whereas-reliable-internal-or-organic-sources
Exception Value: 'SessionStore' object has no attribute 'GET'
答案 0 :(得分:1)
这里有两个错误:
request.session.GET.get(..)
,因为SessionBase
对象具有 no GET
属性;和'session_key'
而不是标识符。您可能想写:
def blog_detail(request, blog_slug):
blog = get_object_or_404(Blog, slug=blog_slug)
session_key = 'blog_views_{}'.format(blog.slug)
if not request.session.get(session_key, False):
blog.blog_views += 1
blog.save()
request.session[session_key] = True
return render(request, 'blogs/blog-detail.html', {'blog':blog})
我们可以使if
语句更短一些,因为默认情况下.get(..)
返回具有真实性None
的{{1}}:
False
因此,这里我们使用def blog_detail(request, blog_slug):
blog = get_object_or_404(Blog, slug=blog_slug)
session_key = 'blog_views_{}'.format(blog.slug)
if not request.session.get(session_key):
blog.blog_views += 1
blog.save()
request.session[session_key] = True
return render(request, 'blogs/blog-detail.html', {'blog':blog})
并使用request.session.get(..)
标识符,而不是文字。如果我们要使用session_key
,我们只需询问会话是否具有密钥'session_key'
而不是'session_key'
。