获取cookie并设置上下文通用视图

时间:2017-02-09 17:10:52

标签: django cookies django-generic-views

我正在实施重复投票检查。我在投票视图中设置了一个cookie:

# Set duplicate vote cookie.
half_year = timedelta(weeks=26)
expires = datetime.utcnow() + half_year
if cookie and re.match(cookie_pattern, cookie):
    redirect.set_cookie(cookie_name, "{}-{}".format(cookie, question.id), expires=expires)
else:
    redirect.set_cookie(cookie_name, question.id, expires=expires)

现在我想访问cookie,而不是在通用详细信息视图中设置上下文变量。这是可能的还是我必须写一个非通用的?

1 个答案:

答案 0 :(得分:0)

结果是覆盖了getcontextobject:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    # Check duplicate vote cookie
    cookie = self.request.COOKIES.get(cookie_name)
    if has_voted(cookie, self.object.id):
        context['voted'] = True
    return context