How to set cookie in django

  • In Django, cookies can be used to store and retrieve information related to a user's session or preferences. Django provides a convenient way to work with cookies through its built-in `HttpRequest` and `HttpResponse` objects.
  • To set a cookie in Django, you can use the `HttpResponse.set_cookie()` method. Here's an example:
views.py


    from django.http import HttpResponse


    def setCookie(request):
        response = HttpResponse("Cookie has been set!")
        response.set_cookie('username', 'JohnDoe')
        return response


    def getCookie(request):
        username = request.COOKIES.get('username')
        if username:
            return HttpResponse(f"Hello, {username}!")
        else:
            return HttpResponse("No username cookie found!")


    def deleteCookie(request):
        response = HttpResponse("Cookie has been deleted!")
        response.delete_cookie('username')
        return response


urls.py



    from django.urls import path
    from .views import setCookie, getCookie, deleteCookie

    urlpatterns = [
        path('set-cookie', setCookie, name='set-cookie'),
        path('get-cookie', getCookie, name='get-cookie'),
        path('delete-cookie', deleteCookie, name='delete-cookie'),
    ]

  • It's important to note that cookies are sent back and forth between the client's browser and the server with every request and response. This means that cookies are susceptible to security risks, such as being intercepted or tampered with. To mitigate these risks, Django provides options for setting secure cookies, limiting cookie access to specific paths or domains, and more.
  • Overall, cookies in Django are a useful mechanism for storing and retrieving data related to a user's session or preferences. They allow you to personalize the user experience and maintain stateful information between requests.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...