Reputation: 157
newbies to django1.6
i want to set cookie in class based generic view (Listview)
models.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
template in template im iterating over objects
so initially objects display in sort_by 'title' desc. "this values is i want to set in cookie".
in template, if user click over title,it will check in cookie cookie['sort_on']='title' then all objects are in asce order
if user click over description,then cookie value is replaced cookie['sort_on']='description' and objects are in desc order..
soo,how to set cookie which i can use in whole ListView class.. ?
Thnx in advance..
Upvotes: 6
Views: 4394
Reputation: 283
In order to set/delete cookies you have to have access to the "response" object. To do so, in a class-based view, you can override "render_to_response".
Example:
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
Upvotes: 10
Reputation: 599926
Unless you have a very good reason, you shouldn't be using cookies, but the session framework. You can access that inside your methods with self.request.session
, and it acts like a dictionary.
if col_nm:
if self.request.session.get('sort_on') == col_nm:
objects=Designation.objects.all().order_by(col_nm).reverse()
else:
self.request.session['sort_on'] = col_nm
objects=Designation.objects.all().order_by(col_nm)
etc.
Upvotes: 2