Marin Leontenko
Marin Leontenko

Reputation: 771

Django view - redirect to one page and open another in new tab

I have a Django view that looks like this:

def edit_view(request, pk)

    # do something ...

    messages.success(request, "Success!")
    return redirect('index')

The view should redirect to "index" (like in the code above), but it should also, at the same time, open another (second) page in new tab.

How can this be achieved?

Upvotes: 0

Views: 1322

Answers (1)

irvoma
irvoma

Reputation: 137

I think this task is not for Django but javascript. For the Django view could be posible to send a JsonResponse containing the redirect link and the new tab one.

{
  "status": "ok",
  "data": {
    "redirect": "/some/redirect/link",
    "new_tab": "/some/new-tab/link"
  }
}

Then use JS

window.open(response.data.new_tab)
window.location.href = response.data.redirect

Expanded Example

I'm assuming you are using a post request, so in your view

from django.http import JsonResponse
from django.urls import reverse

def edit_view(request, pk)
    ...
    if request.method == 'POST':
        # do something ...
        return JsonResponse({
            "status": "ok",
            "data": {
                "redirect": reverse('app:some_view'),
                "new_tab": reverse('app:some_other_view')
            }
        })

In your template, the post must be using promises through the Fetch API

<script>
  def aysncPost(url) {
    fetch(url, {method: 'post'})
    .then(response => response.json())
    .then(data => {
      ...
      window.open(data.new_tab);
      window.location.href = data.redirect;
    });
  }
</script>

Here you have some useful docs

Upvotes: 2

Related Questions