一些背景知识:过去几周我一直在研究tangowithdjango.com教程,并坚持如何让Chrome出现在Chrome中的“开发人员工具”小部件上浏览器。我在Mac OS X Mountain Lion上运行Python 2.7.5和Django 1.5.4。
现在解决手头的问题:我正在使用Django构建一个网页作为教程的一部分。我坚持的当前练习要求我做一些饼干工作。我使用教程中给出的代码来设置一个站点访问计数器,当用户访问我的站点时,该计数器每天增加一次。以下是我的index.html页面(主页)的views.py
文件中的代码:
def index(request):
context = RequestContext(request)
category_list = Category.objects.all()
top_five_cats = Category.objects.order_by('-views')[:5]
if enc_bool == False:
EncodeUrl(category_list, top_five_cats)
context_dict = {'categories': category_list, 'top_five_cats': top_five_cats}
# Obtain our Response object early so we can add cookie information.
response = render_to_response('rango/index.html', context_dict, context)
#-----IMPORTANT CODE STARTS HERE:-----
# Get the number of visits to the site.
# We use the COOKIES.get() function to obtain the visits cookie.
# If the cookie exists, the value returned is casted to an integer.
# If the cookie doesn't exist, we default to zero and cast that.
visits = int(request.COOKIES.get('visits', '0'))
print "visits: ",visits
# Does the cookie last_visit exist?
if 'last_visit' in request.COOKIES:
# Yes it does! Get the cookie's value.
last_visit = request.COOKIES['last_visit']
print "last visit: ", last_visit
print
# Cast the value to a Python date/time object.
last_visit_time = datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S")
# If it's been more than a day since the last visit...
if (datetime.now() - last_visit_time).days > 0:
# ...reassign the value of the cookie to +1 of what it was before...
response.set_cookie('visits',visits+1)
# ...and update the last visit cookie, too.
response.set_cookie('last_visit', datetime.now())
else:
# Cookie last_visit doesn't exist, so create it to the current date/time.
response.set_cookie('last_visit', datetime.now())
return response
#-----IMPORTANT CODE ENDS-----
注意:请从评论“重要代码在这里开始”中开始阅读
我应该看到的内容如下:
注意last_visit
和visits
Cookie是如何显示的。一旦我运行代码,这些是我在开发人员工具上看不到的。下图说明了我在网络浏览器上看到的内容:
有人可以向我解释为什么即使我的代码在views.py
中明确设置后我也无法看到这两个Cookie吗?
答案 0 :(得分:1)
您检查last_visit cookie是否已存在,并且仅在更新时才更新。如果没有怎么办?你是第一次在哪里创建它?
我怀疑是缩进错误:最后一个else
块应该是左边的一个级别,因此如果last_visit不存在则会运行,如评论所示。