【问题标题】:Can't redirect using urls patterns无法使用 url 模式重定向
【发布时间】:2021-06-01 22:59:35
【问题描述】:

当我尝试转到 http://127.0.0.1:8000/1395ec37e4/ 时出现错误:页面未在 ... 我不知道为什么,两次,当我将变量 getted_short_url 更改为 short_urlin urls.py 和 views.py(redirect_view) 时,它可以重定向我。我很困惑……

来自页面的日志:

Using the URLconf defined in cut_and_go.urls, Django tried these URL patterns, in this order:
     <str:getted_short_url>
     admin/

The current path, 1395ec37e4/, didn't match any of these.

views.py:

from hashlib import sha256

from .models import URL
from .forms import URLInput
from django.shortcuts import render, redirect


def input_form(request):
    if request.method == 'POST':
        form = URLInput(request.POST)
        if form.is_valid():
            getted_url = form.cleaned_data["full_url"]
            transformed_url = 'https://' + getted_url
            try:
                URL.objects.get(full_url=transformed_url)
            except URL.DoesNotExist:
                maked_url = sha256(transformed_url.encode()).hexdigest()[:10]
                URL(full_url=transformed_url, short_url=maked_url).save()
    else:
        form = URLInput()
    return render(request, 'shortener/input_form.html', {'form': form})


def redirect_view(request, getted_short_url):
    return redirect(URL.get_full_url(getted_short_url))

urls.py:

from . import views
from django.urls import path

urlpatterns = [
    path('', views.input_form),
    path('<str:getted_short_url>', views.redirect_view)
]

【问题讨论】:

  • 试试'&lt;str:getted_short_url&gt;/'(注意尾随斜线/

标签: django


【解决方案1】:

str 路径转换器无法捕获 URL 末尾的 / 字符。如果您只想匹配/ 之前的部分,请添加一个包含/ 的第二个urlpattern(如果您不关心不以/ 结尾的URL,则替换现有的)。如果您想在路径参数中捕获此斜杠,请使用path 而不是str。请参阅Django docs 了解更多信息。

【讨论】:

    猜你喜欢
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 2023-04-11
    • 2014-05-06
    相关资源
    最近更新 更多