Python Question

Redirect error with django. Nothing seems to work

I know there are many post about django redirecting. However I did not find anything like my problem. I don't know what's happening but I've read a lot and still haven't found anything about it.


So I post my code.


My project urls.py:

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


My app 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'),
]


My app 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


The error appearing on console:

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


The error on browser:

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


I don't understand. I am sending the args it requires, right? I've been stuck for a while now.

Answer

Nope, you are trying to access this URL:

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

with arguments that it does not expect, as it does not expect any arguments.

Have a look at this post, specifically the Sending Parameters to Views topic. It will help you understand why you can't send arguments to the view in this URL.

By the way, what you probably want is to send query params in your request to this URL. In this case, instead of:

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

you will have to do:

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