Talha Ahmed
Talha Ahmed

Reputation: 85

How to set cookie values and then immediately redirect to the next page and display what's in them

So I need to store two variables from one view and redirect to another view and display them. The obvious solution would be to use sessions but I don't have access to sessions because I don't have a database for this project so I'm trying to do sessions client sided because this isn't really a security issue anyways. This is my attempt so far:

View where I set the cookies:

            response = HttpResponse('/result')
            response.set_cookie('passes', True)
            response.set_cookie('errors', [])
            v = jsonschema.Draft4Validator(schema)
            #Uses lazy validation to add all errors to validationErrors array
            for error in v.iter_errors(jsonFile):
                validationErrors.append(error)
                response.set_cookie('passes', False)
            for error in validationErrors:
                error.schma_path = error.schema_path.__str__()[5:]
                print error.schma_path
                print error.schema_path
            response.set_cookie('errors',validationErrors)
            ... 
            return redirect('/result')

View where I try to get the cookies:

passes = request.COOKIES.get('passes',"Doesn't Exist")
errors = request.COOKIES.get('errors', "Doesn't Exist")
return render(request, 'result.html', context = {'errors': errors, 'passes': passes})

passes and errors isn't set because they both return Doesn't Exist. How would I do this without returning to the original page? I don't want to return response where response = render_to_response(current view's template) because it defeats the purpose of what I'm trying to do.

Upvotes: 0

Views: 484

Answers (1)

Lemayzeur
Lemayzeur

Reputation: 8525

You are not getting any cookies values, because actually after assigning the response a cookie, the function returns another Http response.

response = HttpResponse('/result') # first Http Response
response.set_cookie('errors', [])
... 
return redirect('/result')  # An other one

In the last line, you return another response.

so you should return the same response:

response = redirect('/result') # redirect is here
response.set_cookie('errors', [])
... 
return response 

Upvotes: 1

Related Questions