python - 如何在基于类的通用 View 中设置 cookie

标签 python django cookies django-views

django1.6 新手

我想在基于类的通用 View ( ListView )中设置 cookie

模型.py

class Designation(Models.model):
    title = models.CharField(max_length=50)
    description = models.CharField(max_length=10000, blank=True)

views.py

class DesignationList(ListVew):

    def get_queryset(self):
        """ 
        will get 'sort_by' parameter from request,
        based on that objects list is return to template
        """

        col_nm = self.request.GET.get('sort_by', None)


        if col_nm:
            if cookie['sort_on'] == col_nm:
                objects=Designation.objects.all().order_by(col_nm).reverse()
            else:
                cookie['sort_on'] = col_nm
                objects=Designation.objects.all().order_by(col_nm)  
        else:
            objects = Designation.objects.all().order_by('title')
            //set cookie['sort_on']='title'


    return objects

模板 在模板中迭代对象

所以最初对象显示在 sort_by 'title' desc 中。 “这个值是我想在 cookie 中设置的”。

在模板中,如果用户点击标题,它会检查cookie cookie['sort_on']='title' 那么所有的对象都是按顺序排列的

如果用户点击描述,则cookie值被替换 cookie['sort_on']='description' 并且对象按降序排列..

那么,如何设置我可以在整个 ListView 类中使用的 cookie..?

提前致谢..

最佳答案

为了设置/删除 cookie,您必须有权访问“响应”对象。为此,在基于类的 View 中,您可以覆盖“render_to_response”。

例子:

class DesignationList(ListVew):
    def render_to_response(self, context, **response_kwargs):
        response = super(LoginView, self).render_to_response(context, **response_kwargs)
        response.set_cookie('sort_on', 'title')
        return response

关于python - 如何在基于类的通用 View 中设置 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22937995/

相关文章:

python - BeautifulSoup:如何提取内容?

python - 使用 setup.py bdist_rpm 删除 Django 测试

jquery - 在 jQuery 中设置一个 cookie

java - 如何在 Android 上使用 cookie 发出 http 请求?

python - djangorest框架用户注册

Javascript cookie 不适用于所有页面

python - [可靠];使用多个字典

python - 如何在 Windows 上为 Apache 安装 Python flip? (使 web.py 工作)

python - ImageScraper 不工作

python - Django ·赫罗库 : No Such File or Directory for image (image is in repo)