Skip to main content
 首页 » 编程设计

python之django 重定向错误。似乎没有任何效果

2025年05月04日34davidwang456

我知道有很多关于 Django 重定向的帖子。但是我没有发现任何类似我的问题。我不知道发生了什么,但我已经阅读了很多,但仍然没有找到任何相关信息。

所以我发布了我的代码。

我的项目 urls.py:

from django.conf.urls import url, include 
urlpatterns = [ 
    url(r'^backbone', include('backbone.urls', namespace='backbone')), 
] 

我的应用程序 urls.py

from django.conf.urls import url 
from . import views 
urlpatterns = [ 
    url(r'^/shell$', views.shell, name='shell'), 
    url(r'^/login$', views.login, name='login'), 
] 

我的应用views.py

def shell(request, app='cashier'): 
    if 'user' not in request.session: 
        response = redirect('backbone:login', app=app) 
    else: 
        response = render(request, 'template.html') 
    return response 
 
def login(request, app): 
    context = { 
        'app': app, 
    } 
    response = render(request, 'backbone/login.html', context) 
    return response 

控制台出现的错误:

django.urls.exceptions.NoReverseMatch: Reverse for 'login' with arguments '()' and keyword arguments '{'app': 'app'}' not found. 1 pattern(s) tried: ['backbone/login$'] 

浏览器报错:

NoReverseMatch at /backbone/shell 
Reverse for 'login' with arguments '()' and keyword arguments '{'app': 'app'}' not found. 1 pattern(s) tried: ['backbone/login$'] 
Request Method: GET 
Request URL:    http://192.168.1.79/backbone/shell 
Django Version: 1.10.3 
Exception Type: NoReverseMatch 
Exception Value:     
Reverse for 'login' with arguments '()' and keyword arguments '{'app': 'app'}' not found. 1 pattern(s) tried: ['backbone/login$'] 
Exception Location: /usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py in _reverse_with_prefix, line 392 
Python Executable:  /usr/bin/python3 
Python Version: 3.5.2 
Python Path:     
['/home/ipi/workspace/RamoSP', 
 '/usr/lib/python35.zip', 
 '/usr/lib/python3.5', 
 '/usr/lib/python3.5/plat-x86_64-linux-gnu', 
 '/usr/lib/python3.5/lib-dynload', 
 '/usr/local/lib/python3.5/dist-packages', 
 '/usr/lib/python3/dist-packages'] 
Server time:    Thu, 24 Nov 2016 19:56:47 +0000 

我不明白。我正在发送它需要的参数,对吗?我已经被困了一段时间了。

请您参考如下方法:

不,您正在尝试访问此 URL:

url(r'^/login$', views.login, name='login') 

带有它不期望的参数,因为它不期望任何参数。

看看this post ,特别是向 View 发送参数主题。它将帮助您理解为什么不能将参数发送到此 URL 中的 View 。

顺便说一下,您可能想要在您的请求中将查询参数 发送到此 URL。在这种情况下,而不是:

redirect('backbone:login', app=app) 

你必须做:

url = '{}?app={}'.format(reverse('backbone:login'), '?item=4') 
redirect(url)