Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Forms More on Models Question and Answer Models

Richard Li
Richard Li
9,751 Points

Reverse: urlpattern name vs. view function

In the Django Docs,

reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)

viewname can be a URL pattern name or the callable view object.

But when I try to change what's in Kenneth code:

reverse('courses:quiz', kwargs={'course_pk':self.course_id, 'step_pk':self.id})

to the following:

from . import views
.........
reverse(views.quiz_detail, kwargs={'courses_pk':self.course.id, 'setp_pk':self.id})

it will always throw back an error:

Reverse for 'courses.views.quiz_detail' not found. 'courses.views.quiz_detail' is not a valid view function or pattern name.

WHY??

and moreoever:

HERE IS THE INTERESTING PART: in previous courses writing views for suggestion:

I used

def suggestion_view(request):
...........
    return HttpResponseRedirect(reverse(suggestion_view))

no errors here.

So when to use reverse(pattern name) and when to use reverse(view function)??

I personally prefer to use view function since it is pretty similar to url_for in flask...

Thanks!!!

Richard Li
Richard Li
9,751 Points

Oh Chris Freeman Please hope you can help me here!!

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,457 Points

According to the docs,

reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)

viewname can be a URL pattern name or the callable view object. For example, given the following url:

from news import views

path('archive/', views.archive, name='news-archive')

you can use any of the following to reverse the URL:

# using the named URL
reverse('news-archive')

# passing a callable object
# (This is discouraged because you can't reverse namespaced views this way.)
from news import views
reverse(views.archive)

But as it says in the above comment, using named URL is the preferred method.

Richard Li
Richard Li
9,751 Points

Thank you so much Chris!!