Django session not available on two seperate requests

2024/11/16 12:29:57

Description:

In the django session docs it says:

You can read it and write to request.session at any point in your view.

But I can't access the session when making a second request to the same view:

views.py

class Login(APIView):def post(self, request):print("before: ", request.session.get("user")request.session["user"] = "admin"print(request.session.get("user")) #outputs 'admin'return Response()

Expected Output:

After the second request (made with jquery $.post) it should output:

"admin"

Output:

Instead it outputs:

None

How can I make sessions available between independend requests?

Answer

As mentioned by @AbdulAzizBarkat in the comments, the problem was that the session credentials were not sent to the backend. The way the sessions work in a cross-domain scenario is:

  • User is verified in backend
  • Session is sent to the frontend and stored in the browser
  • The session credentials have to get sent to the backend on every request

You cannot, however, read this session cookies, like mentioned here:

The browser cannot give access to 3rd party cookies like those received from ajax requests for security reasons, however it takes care of those automatically for you!

The provided solution using ajax and setting xhrFields: { withCredentials: true } did not work for me.

Answer:

Instead of an ajax request, I used fetch requests.

It is important to set credentials: "include" since otherwise cookies won't be sent cross-origin. A request looks like this:

fetch(`${API}/login`, {credentials: "include",method: "POST",body: data,
}).then(...).catch(...);
https://en.xdnf.cn/q/119195.html

Related Q&A

Counting how many times there are blank lists in a list of list [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Generating a list of random permutations of another list

So, Im trying to tackle the TSP with a Genetic Algorithm. To do that I need to create a population pool. What I want to accomplish is to create a list of random permutations that will represent a popul…

How to hide location of image in django?

models.py class UserInfo(models.Model):UID = models.CharField(max_length=50, primary_key=True, default=datetime.now().strftime("%d%y%H%S%m%M")) # default=fullname = models.CharField(max_leng…

Extracting data from multiple files with python

Im trying to extract data from a directory with 12 .txt files. Each file contains 3 columns of data (X,Y,Z) that i want to extract. I want to collect all the data in one df(InforDF), but so far i only …

Python: Checking if string follows wikipedia link format

If I have a string named link, how would I go about checking to see if it follows the same format as a wikipedia URL? To clarify, wikipedia URLs (in this case) always begin with en.wikipedia.org/wiki/…

Create dictionary comprehension from list with condition syntax

Id like to create a dictionary using dictionary comprehension syntax.Note that list l contains tuples of strings and tuples with 1st element always a time stamp.This works:d = {} for entry in l:if entr…

How to find next empty cell on a specific column and write to it?

I want to find the next empty cell in a specific column and write to values that cell. Ive tried it using following method: for row in sheet[A{}:A{}.format(sheet.min_row,sheet.max_row)]:if row is None:…

How can i pass data from template in Django to Javascript in this specific case

I am using Google map api and i am trying to pass the data (longitude and latitude) to the template then use the data in the javascript to show a specific location.location.html{% for venue in propert…

Python Highscores w/ text file

i am currently working on a text based game, and have run into a problem trying to make my last function, highscore. My problem is this, i would like to make the function save my top five scores and sa…

Do any one know about this Error in python? how can I resolve this?

I am plotting the data with MapBoxGl Python Library on maps, here is my code which is taking the latitude, longitude and points from the Pandas DataFrame and trying to make the geojson, here is the cod…