Home > OS >  DRF - How to redirect a user after already sending a response
DRF - How to redirect a user after already sending a response

Time:11-05

I'm facing the following problem: I'm building a third-party integration into my Django app. Users that already use the third-party should be able to click on a button and be redirected to my app. In the redirect, the third-party will send a POST request with a JSON that contains some info (email, some IDs etc.).

I'll use this info to see if I have the user in my DB already.

If yes, I want to:

  • return a response with a user ID and API Key for the third party to store
  • then redirect the user to a login screen

If no, I want to:

  • create a user and return a response with a user ID and API Key for the third party to store
  • then redirect the user to a confirmation screen.

The question I have: How can I redirect the user AFTER returning the user ID & API key?

My current logic is this:

class UserList(APIView):
    ....

    def post(self, request):
        if account_exists:
            return Response(account_data)
            # NOW I WANT TO REDIRECT
        else:
            create_account()
            return Response(account_data)
            # NOW I WANT TO REDIRECT

I'm currently using DRF to handle the POST requests, not sure whether that is the best way of doing it though?

CodePudding user response:

Part1 in case of true if statement: use HTTPResponseRedirect from django.http import HttpResponseRedirect

After passing your data third party, return HTTPResponseRedirect(yourdesiredurl)

Part2 for false if statement or else statement:

For redirecting the user to a confirmation screen, try JsonResponse

from django.http import JsonResponse

at end of your function you use it with return statement as this:

return JsonResponse("Confirmation of XXXX", safe = False)

anything you write within commas, will be displayed on a new template to the user.

CodePudding user response:

You are Using DRF, I guess you build backend APIs' here and you may be using a frontend client.

You don't have to redirect users in your backend api, you will have to do this at the frontend application.

My first solution- I will include a third data along with user ID and API Key to send back to the user, let's name this xyz. Now if account_exists is true, send the response TRUE as the value of xyz, or else send false as the value of xyz.

Now at the frontend read the value of xyz and use javascript to redirect the users.

** This is just an example you can apply relevant logic by yourself.
  • Related