如何在Django中重定向到外部URL? [英] How to redirect to external URL in Django?

查看:672
本文介绍了如何在Django中重定向到外部URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这应该很容易,但是我无法弄清楚。我正在尝试写一个退出视图。我收到一个获取请求。通过urls.py,我呈现了退出视图。在此视图中,我将用户的一些参数保存在数据库中,然后将用户重定向到外部URL。我尝试过:

I think this should be easy, but I cannot figure it out. I am trying to write an opt-out view. I am receiving a get request. Through urls.py, I render my opt-out view. In this view, I save some parameters for the user in the database and then I want to redirect the user to an external URL. I tried:

return redirect('http://stackoverflow.com/')

来自 Django文档。但是,尽管参数按预期方式保存在数据库中,但选择退出视图将呈现训练模板而不是返回重定向。我的代码如下:

from Django documentation. However, the optout view renders the training template instead of returning the redirect, though the parameters are saved in the database as expected. My code is as follows:

def optout(request):
    if (('REMOTE_USER' in request.META and request.META['REMOTE_USER'] != "") or 
        (request.session.get('userid', False) and request.session['userid'] != "")):
        if ('REMOTE_USER' in request.META and request.META['REMOTE_USER'] != ""):
            userid = request.META['REMOTE_USER']
        if (request.session.get('userid', False) and request.session['userid'] != ""):
            userid = request.session['userid']
        user = User.objects.get(username=userid)
        user.optout = True
        user.postpone = False
        user.save()
        return redirect('http://stackoverflow.com/')
    context = { 'userid': "" }
    return render(request, 'games/Training.html', context)

我们非常感谢您的帮助。

Any help is highly appreciated.

推荐答案

是的,返回redirect('http://stackoverflow.com /’)是正确的方法。

Yeah, return redirect('http://stackoverflow.com/') is the correct method.

如果执行以下操作,则可以确认这是一种有效的重定向方法。

If you do the following, you can confirm that is a working method to redirect.

   from django.shortcuts import redirect

   def optout(request):
       return redirect("http://stackoverflow.com/")

您的条件语句一定不能被捕获。

Your conditional statements must not be catching.

这篇关于如何在Django中重定向到外部URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆