Django Cookies Django.How

Author avatar wrote on 31/05/2022

Set cookies

set_cookie(cookie_name, value, max_age = None, expires = None)

Get cookies

request.COOKIES[‘cookie_Name’]

Views example

def SetCookie(request):
    response = HttpResponse('Visiting for the first time')
    response.set_cookie('bookname','Sherlock Holmes')
    return response
 
def GetCookie(request):
    bookname = request.COOKIES['bookname']
    return HttpResponse(f'The book name is: {bookname}')

Login example


from django.template import RequestContext

def login(request):
    username = "not logged in"
    
    if request.method == "POST":

Get the posted form

        MyLoginForm = LoginForm(request.POST)
    
    if MyLoginForm.is_valid():
        username = MyLoginForm.cleaned_data['username']
    else:
        MyLoginForm = LoginForm()
    
    response = render_to_response(request, 'loggedin.html', {"username" : username}, 
    context_instance = RequestContext(request))
    
    response.set_cookie('last_connection', datetime.datetime.now())
    response.set_cookie('username', datetime.datetime.now())
        
    return response

Redirect to login form if no cookies

   def formView(request):
   if 'username' in request.COOKIES and 'last_connection' in request.COOKIES:
      username = request.COOKIES['username']
      
      last_connection = request.COOKIES['last_connection']
      last_connection_time = datetime.datetime.strptime(last_connection[:-7], 
         "%Y-%m-%d %H:%M:%S")
      
      if (datetime.datetime.now() - last_connection_time).seconds < 10:
         return render(request, 'loggedin.html', {"username" : username})
      else:
         return render(request, 'login.html', {})
			
   else:
      return render(request, 'login.html', {})

Resource:
  • https://www.askpython.com/django/django-cookies
  • CRUDgen Django CRUD generator