【问题标题】:django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern namedjango.urls.exceptions.NoReverseMatch:找不到''的反向。 '' 不是有效的视图函数或模式名称
【发布时间】:2021-05-18 00:48:27
【问题描述】:

我正在尝试创建一个 url-shohrtener,但它给了我这个错误:

django.urls.exceptions.NoReverseMatch:找不到“”的反向。 '' 不是有效的视图函数或模式名称。

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('shorturl.urls')),
]

这是我的应用程序 urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('<str:id>/', views.redirect_url, name='redirect'),
]

这些是views.py:

from django.shortcuts import render, redirect
from .models import Url
import random
import string

def redirect_url(request, id):
    urls = Url.objects.filter(short=id)
    link = ""
    for i in urls:
        link = i.url
    return redirect(link)

def index(request):
    if request.method == "POST":
        link = request.POST.get("link")
        short = ""
        if Url.objects.filter(url=link).exists():
            urls = Url.objects.all()
            for i in urls:
                if i.url == link:
                    short = i.short
                    break
        else:    
            short = get_short_code()
            url = Url(url=link, short=short)
            url.save()
        new_url = request.get_host() + "/" + short
        return render(request, 'shorturl/index.html', {"new_url":new_url})

    return render(request, 'shorturl/index.html')

def get_short_code():
    length = 6
    char = string.ascii_uppercase + string.digits + string.ascii_lowercase
    while True:
        short_id = ''.join(random.choice(char) for x in range(length))
        if Url.objects.filter(short=short_id).exists():
            continue
        else:
            return short_id 

以防万一这是模板很重要:

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

    <title>Shroten URL</title>
    <script>
      function myFunction() {
        /* Get the text field */
        var copyText = document.getElementById("myInput");

        /* Select the text field */
        copyText.select();
        copyText.setSelectionRange(0, 99999); /* For mobile devices */

        /* Copy the text inside the text field */
        document.execCommand("copy");
      }
    </script>
  </head>
  <body>

    <div class="container" style="padding-top: 5%;">
        <form method="POST">
            {% csrf_token %}
            <div class="mb-3">
            <label for="exampleInputEmail1" class="form-label">Link</label>
            <input name="link" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
            </div>
            <button type="submit" class="btn btn-primary">Shorten</button>
        </form>
        {% if new_url %}
          <div class="mb-3">
            <label for="exampleInputEmail1" class="form-label">Short Link</label>
            <input name="link" type="text" value= {{new_url}} class="form-control" id="myInput" aria-describedby="emailHelp">
          </div>
          <button onclick="myFunction()" class="btn btn-primary">COPY</button>
          
        {% endif %}
    </div>
    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js" integrity="sha384-q2kxQ16AaE6UbzuKqyBE9/u/KzioAlnx2maXQHiDX9d4/zp8Ok3f+M7DPm+Ib6IU" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.min.js" integrity="sha384-pQQkAEnwaBkjpqZ8RU1fF1AKtTcHJwFl3pblpTlHXybJjHpMYo79HY3hIi4NKxyj" crossorigin="anonymous"></script>
    -->
  </body>
</html>

我在终端上得到的错误网站工作正常。 整个错误是:

Traceback (most recent call last):

File
"C:\Users\Dell\Desktop\new\xp\lib\site-packages\django\core\handlers\exception.py",
line 47, in inner
    response = get_response(request)   File "C:\Users\Dell\Desktop\new\xp\lib\site-packages\django\core\handlers\base.py",
line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "C:\Users\Dell\Desktop\new\xp\Url-shortener\shorturl\views.py", line
12, in redirect_url
    return redirect(link)   File "C:\Users\Dell\Desktop\new\xp\lib\site-packages\django\shortcuts.py",
line 41, in redirect
    return redirect_class(resolve_url(to, *args, **kwargs))   File "C:\Users\Dell\Desktop\new\xp\lib\site-packages\django\shortcuts.py",
line 131, in resolve_url
    return reverse(to, args=args, kwargs=kwargs)   File "C:\Users\Dell\Desktop\new\xp\lib\site-packages\django\urls\base.py",
line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))   File "C:\Users\Dell\Desktop\new\xp\lib\site-packages\django\urls\resolvers.py",
line 685, in _reverse_with_prefix
    raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern
name.

请帮我解决这个问题。

【问题讨论】:

  • urls = Url.objects.filter(short=id) 不应该是urls = Url.objects.get(short=id) 吗?即 short 应该是唯一的。对于 short pass 的值,可能不存在这样的实例。请改用get_object_or_404(Url, short=id)。如果不存在这样的模型实例,它将简单地给出 404。
  • 我们可以通过两种方式做到这一点。filter() 给出了一个查询集,所以我使用了一个 for 循环来获取短变量
  • .filter() 给出了一个查询集,但在您的用例中,short 是唯一的,您只需要一个结果。当你可以简单地得到你想要的结果时,为什么要无缘无故地循环呢? (如果您的模型中没有短字段,也可以输入unique=True)此外,使用.get() 的好处是它假设只会出现一个结果。如果你得到多个或没有,它会引发异常。当然,过滤器对此没有任何问题。
  • 谢谢我会改变它...

标签: python python-3.x django


【解决方案1】:

在 urls.py 中而不是 path('&lt;str:id&gt;/', views.redirect_url, name='redirect') 中使用 path('l/&lt;str:id&gt;/', views.redirect_url, name='redirect') 之类的东西,因为在您访问网站时会在 id 的位置传递空值,这会触发除 index 函数之外的 redirect_url 函数。在 url 模式中传递 /l/ 之类的内容可以解决问题。

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 2018-03-29
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    相关资源
    最近更新 更多