3

new to django

so this one probably has a very simple answer but i cannot for the life of me find the specific solution to this. I am simply trying to redirect to a new URL after a form submission with a FileField.

I can navigate to the URL separately and it works fine.

The file uploads correctly so I know it is validated correctly.

But the redirect returns the following error:

Reverse for 'success' not found. 'success' is not a valid view function or pattern name.

I have tried a bunch of different naming conventions, but none has worked. It looks to me like I have setup the URL and passed it correctly.

Would really appreciate some help with this. The simplest problems are the most frustrating!

Here are the views.

from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .forms import InvestmentReportForm

def upload(request):
    if request.method == 'POST':
        form = InvestmentReportForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()

            return redirect('success')
    else:
        form = InvestmentReportForm()
    return render(request, 'app/upload.html', {'form': form})

def success(request):
    return HttpResponse("File successfully uploaded")

And my urls.py:

app_name = 'app'
urlpatterns = [
                path('', views.index, name='index'),
                path('upload/', views.upload, name='upload'),
                path('success/', views.success, name='success'),
                path('performance/', views.performance, name='performance'),
                ]
Ryan Skene
  • 864
  • 1
  • 12
  • 29
  • OK, so what do you see if you add success_url = reverse('success') right before return redirect('success')? You would need to assert False to see the value of success_url – EarlyCoder Jan 01 '18 at 18:04
  • Do those url patterns have a namespace? – Daniel Roseman Jan 01 '18 at 19:04
  • do u mean did i provide an app_name in my urls.py? if so, yes. ill update the code. – Ryan Skene Jan 01 '18 at 21:23
  • alrite so i tried this `return redirect('app:success')` and it worked. so if you do namespace a set of URL patterns, you have to refer to that namespace when you try to call the url. if you want to make it answer, i'll accept it. – Ryan Skene Jan 01 '18 at 21:50

2 Answers2

7

The answer was simple as I suspected. For others, if you use a namespace for a set of url patterns, you have to refer to that namespace when calling those urls. For this example:

return redirect('app:success')

Ryan Skene
  • 864
  • 1
  • 12
  • 29
1
def upload(request):
    if request.method == 'POST':
        form = InvestmentReportForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()

            return HttpResponseRedirect('success/')
    else:
        form = InvestmentReportForm()
    return render(request, 'app/upload.html', {'form': form})
Marin
  • 1,098
  • 14
  • 33