10

I need to do an HTTP call using AJAX with an already authenticated user using Django.

Is there any standard simple way to do this? I've read this other question but uses a different technology.

I'm using HTTP (not HTTPS) and using a third-party app like django-tastypie for this unique "simple" purpose would be overkill, wouldn't it?

Community
  • 1
  • 1
Caumons
  • 9,341
  • 14
  • 68
  • 82

2 Answers2

13

Ajax requests are no different from any other kind of request. If the user is already authenticated, then the Ajax request will be authenticated too: the session cookie which identifies the user will be sent along with the Ajax request just as it would be with any other one.

(That linked question is irrelevant because it is talking about authenticating the user within the request, not using an already-authenticated user as you want.)

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thanks for your answer, I've got it working now! :) For some reason the request was failing and I thought it was because the Ajax request wasn't using the authenticated user, but it actually does it as expected and as you explained. The only "caveat" is that the jQuery's `fail()` error handler is never called, but this would be another question... – Caumons Aug 24 '13 at 14:00
  • 1
    [@Daniel Roseman](https://stackoverflow.com/users/104349/daniel-roseman): I have tried to make Ajax call with 'GET' and I tried to print request.user in my python view function but I am getting the **SimpleLazyObject** only. May I know why I am getting like this. – Mohammed Yasin May 08 '19 at 05:54
0

For this, you would simple make an AJAX call to your URL, and in the view that handles the URL, you would add the @login_required decorator. For some reason, the django project is down right now, so I will send you to another place where you can get the information.

However, you will need to watch out for a few things, one is that you need to add the CSRF token, and secondly you will need to make a few changes in the SETTINGS.PY file.

I think the video covers it all, sorry I cannot send you to the official docs, because it seems to be down at the moment.

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
  • Thanks for your answer. I'm already using `@login_required`. And as I'm doing a `POST` without using a form I'm also using `@csrf_exempt`. @DanielRoseman's answer completelly solved my doubt! – Caumons Aug 24 '13 at 14:02