I want to set a cookie if user is logged in or not.
user_status = 1 if request.user.is_authenticated() else 0
max_age = (20)*52*7*24*60*60 # 20 years (After expiry, cookie gets deleted)
According to the FineManual:
During the response phases (process_response() and process_exception() middleware), the classes are applied in reverse order, from the bottom up
So I'd say you'd better add your middleware before the auth and session middlewares (assuming it only processes the response).
This being said, I'm a bit puzzled by the fact that you only have the error on some pages ???