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

Get cookie and set context generic view

我正在实施重复投票检查。我在投票视图中设置了一个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,然后在通用详细信息视图中设置上下文变量。这可能吗,还是我必须写一个非通用的?

解决方案是覆盖 js 上下文对象:

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