简体   繁体   中英

Django NoReverseMatch Error when passing arguments on redirect

Hi im trying to redirect from one view function to another and passing a list of lists as argument.

urls.py

    urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^checkFiles/', views.checkFiles, name='checkoutFiles'),
    url(r'^$', views.home, name='home'),
    url(r'^upload/', views.upload, name='upload'),
    url(r'^login', views.loginview, name='loginview'),
    url(r'^logout/', views.logoutview, name='logoutview'),
    url(r'^confirm_files/', views.upload, name='confirm_file'),
    url(r'^upload/', views.del_files, name='del_files'),

]

views.py

for redirecting from views.upload to views.checkoutFiles i'm using this command

return redirect(reverse('checkoutFiles', kwargs={'ACCEPTED_FILES':ACCEPTED_FILES}))

...

def checkFiles(request, ACCEPTED_FILES):
  print ACCEPTED_FILES
  return render(request, 'confirm_files.html', {
      'ACCEPTED_FILES': ACCEPTED_FILES
  })

and im getting this error message

NoReverseMatch: Reverse for 'checkoutFiles' with keyword arguments '{'ACCEPTED_FILES': [[u't2_r0Oqwl7.txt', '0.98 KB', u'text/plain']]}' not found. 1 pattern(s) tried: ['checkFiles/']

django version: 1.11.2

When you call reverse, Django follows what you have in urls.py. In there you don't have any parameters specified in the regular expression for checkoutFiles . For example:

url(r'^articles/([0-9]{4})/$', views.year_archive, name='year-archive'),

In this example you can call:

reverse('year-archive', args=[datetime.datetime.today().year])

https://docs.djangoproject.com/en/1.11/topics/http/urls/#example

In your code you must specify what are the parameters you'll receive in that URL.

url(r'^checkFiles/(?P<extension>[\w]+)/$', views.checkFiles, name='checkoutFiles'),

Although it would not be a good idea doing this kind of validation through a URL.

Edit #2

If you want to have something in the URL, you can use a GET parameter:

Whenever you redirect you can do something like this:

return redirect(reverse('checkoutFiles') + '?files={}'.format(ACCEPTED_FILES))

In the view where you are redirected to, you can get the values with

request.GET.get('files', '')

https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.GET

You should add a namespace in you project urls.py file and also in below code
Example: project_name/urls.py

url(r'^appname/', include('appname.urls', namespace='namespace')),

views.py

 return redirect(reverse('namespace:checkoutFiles', kwargs={'ACCEPTED_FILES':ACCEPTED_FILES}))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM