重定向到外部网站时,url 会附加到所请求的 url 的末尾

When redirecting to external website the url gets appended to the end of the requested url

我正在尝试将用户重定向到 URl,但它却将我重定向到不正确的 url。

views.py:

def redirect_shortner(request):
    return redirect('www.google.com')

url.py:

urlpatterns = [
    path('', redirect_shortner, name='redirect_shortner'),
]

代码对我来说似乎是正确的,但用户被错误地重定向到 url,当前 url 附加了指定的 url,即用户被重定向到 http://127.0.0.1:8000/www.google.comhttp://127.0.0.1:8000/ 是当前 url.

当一个人想重定向到其他网站时,应该提供absolute url(见问题Absolute vs relative URLs)其他网站。 www.google.com 不是绝对的 url,即它缺少协议 https:// 因此它被认为是来自 relative url用户当前所在的页面,因此解析为 http://127.0.0.1:8000/www.google.com。相反,您想将重定向写成绝对的:

def redirect_shortner(request):
    return redirect('https://www.google.com/')