Django视图-重定向到一个页面,然后在新选项卡中打开另一个页面



我有一个Django视图,看起来像这样:

def edit_view(request, pk)
# do something ...
messages.success(request, "Success!")
return redirect('index')

视图应该重定向到";索引";(就像上面的代码一样(,但同时也应该在新选项卡中打开另一个(第二个(页面

如何做到这一点?

我认为这个任务不是针对Django的,而是针对javascript的。对于Django视图,可以发送一个JsonResponse,其中包含重定向链接和新的选项卡链接。

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

然后使用JS

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

扩展示例

我假设你正在使用一个帖子请求,所以在你看来

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')
}
})

在您的模板中,帖子必须通过Fetch API使用promise

<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>

这里有一些有用的文档

Django JsonResponse
  • 获取API
  • 相关内容

    最新更新