I have two simple views:
def form_view(request):
form = MyModelForm()
if request.method == "POST":
form = MyModelForm(request.POST)
if form.is_valid()
form.save()
uuid = uuid4()
request.session["uuid"] = uuid.hex
return HttpResponseRedirect(reverse("thanks"))
return render(request, "form.jinja2", {"form": form})
# the url obtained by reverse("thanks") maps to this view
def redirect_view(request):
if "uuid" in request.session: # this returns false in prodcution
return render(request, "thanks.jinja2", {"uuid": request.session["uuid"]}
return redirect("/")
The code works in development, i.e I can fetch data from request.session, but in production it does not work, and I can’t seem to figure out why.
I have tried to set request.session.modified = True
, set SESSION_COOKIE_SECURE = False
in settings and also tried using request.session.set_test_cookie()
and request.session.test_cookie_worked()
in the two different views, i.e setting the cookie in form_view
and testing the cookie in redirect_view
, but it returned false. Interestingly, if I do this:
def form_view(request):
form = MyModelForm()
if request.method == "POST":
print(request.session.test_cookie_worked()) # this prints True!
form = MyModelForm(request.POST)
if form.is_valid()
form.save()
uuid = uuid4()
request.session["uuid"] = uuid.hex
return HttpResponseRedirect(reverse("thanks"))
request.session.set_test_cookie()
return render(request, "form.jinja2", {"form": form})
The test_cookie_worked()
returns True
.
I have tried many of the solutions recommended when searching on something similar, but none of these work for me, and I don’t know what else to try.
Relevant settings for both environments are:
SESSION_COOKIE_SECURE = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_COOKIE_AGE = 60 * 60
SECURE_SSL_REDIRECT = True
CSRF_COOKIE_SECURE = True
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
Both the production environment and development are running over https.