So basically from what I read across the internet, Django cookies are stored in the sessions I guess, and when we try to access them what so ever, there will be sessionid in the cookies and it makes the cookies (like accessing the user stored in the request and stuff) achievable. My problem is that I have a front-end, and in that I try to get the data of a ‘Post’. The problem is that in my GET request, from what I invested, there are no cookies sent to the back-end, and because of that, the sessionid is gone and my user that is stored (or better to say must be stored) in the request is gone (AnonymousUser it is). The fun fact is there is another view in my Django app for logout, which works prefect and the request does have the sessionid and access to the user in the request. My question is, is this a problem with my views ?! Is it general ?! What is causing this to happen ?! I really need this to be fixed, cause all my project is actually getting collapsed because of this problem I have with fetching data.
How do I send request to get the data of ‘Post’:
export async function getPostByID(id: string) {
const apiToken = await getCSRFToken();
const response = await fetch(
"http://localhost:8000/posts/?id=" + id,
{
method: "GET",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": apiToken,
},
credentials: "include",
}
);
const respnse = await fetch(
"http://localhost:8000/posts/comments",
{
method: "GET",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": apiToken,
},
credentials: "include",
}
);
const data = await response.json();
return data;
}
How do I handle the request the get the data of ‘Post’ (Because some objects weren’t JSON Serializable, I had to make a dictionary myself):
class PostsView(View):
def get(self, request):
id = request.GET.get('id')
if id is not None:
post = get_object_or_404(Post ,id=id)
comments = []
for comment in post.comments.all():
comments.append({
'id': comment.id,
'author': comment.author.username,
'post': comment.post.id,
'content': comment.content,
'created_at': comment.created_at,
'updated_at': comment.updated_at
})
try:
Like.objects.get(author=request.user.id, post=post.id)
liked = True
except Like.DoesNotExist:
liked = False
return JsonResponse({'id': post.id, 'author':{'id': post.author.id, 'email': post.author.email, 'username': post.author.username}, 'title': post.title, 'content': post.content, 'comments': comments, 'created_at': post.created_at, 'updated_at': post.updated_at, 'likes': post.getLikesCount(), 'liked': liked}, status=200)
userID = request.GET.get('user')
if userID is not None:
user = get_object_or_404(User, id=userID)
posts = get_list_or_404(Post, author=user)
return JsonResponse({'posts': posts}, safe=False, status=200)
posts = Post.objects.all()
response = {'posts': []}
for post in posts:
response['posts'].append({'id': post.id, 'author':{'id': post.author.id, 'email': post.author.email, 'username': post.author.username}, 'title': post.title, 'content': post.content, 'created': post.created_at, 'updated': post.updated_at, 'likes': post.getLikesCount()})
return JsonResponse(response, status=200)
And this is the way I am sending the logout request:
front-end:
async function handleLogout() {
const apiToken = await getCSRFToken();
const reponse = await fetch("http://localhost:8000/accounts/logout/", {
method: "GET",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": apiToken,
} as any,
credentials: "include",
});
const data = await reponse.json();
if (!reponse.ok) {
toast.error(data.message, {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: false,
pauseOnHover: false,
draggable: false,
progress: undefined,
theme: "dark",
transition: Flip,
});
return;
} else {
toast.success(data.message, {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: false,
pauseOnHover: false,
draggable: false,
progress: undefined,
theme: "dark",
transition: Flip,
});
context.setUser(undefined);
}
}
Back-end:
class LogoutView(View):
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return JsonResponse({'message': 'Not logged in!'}, status=401)
return super().dispatch(request, *args, **kwargs)
def get(self, request):
logout(request)
return JsonResponse({'message': 'Successfully logged out.'}, status=200)
The only difference is that the logout is handled through a button, and in a client component which is navbar, and fetching data for ‘Post’ is handled in a server component and then the data returned is passed to another component to show them.
My Django, Python, NextJS, React, and everything is the latest.
Also I must say that I know that it is better to make back-end using Django-rest framework, but this was a quick and small project so I just wanted to use the Django itself instead.
I modified the settings of Django with somethings like “COOKIE_SESSION_SAMESITE = None” and it didn’t work, tried to send request in other ways with modifications and it didn’t work, and a lot of other things that I actually don’t remember because I am trying to handle this for a few days now.
Also I used the django-cors-headers library so there is no problem with the CORS here.