Paggie
Paggie

Reputation: 11

What's the difference between Reverse vs. Redirect in Django?

I am doing a django project, and is very confused about reverse, reverse_lazy and redirect.

Can redirect function redirect with parameters? Or should I change method to reverse whenever I want to post parameters?

Upvotes: 1

Views: 905

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

Can redirect function redirect with parameters?

Yes. Imagine that you have a url pattern with:

 path('foo/<str:bar>/<id:pk>/', name='some_path')

you can redirect to that path with:

    return redirect('some_path', bar='value-for-bar', pk=1425)

is very confused about reverse, reverse_lazy and redirect.

reverse and reverse_lazy determine the path for a given view name. That path is a string, not a HTTP response, you can not return such string as a result for a view.

The redirect(…) function [Django-doc] will call reverse(…) function [Django-doc] internally and wrap the result in a HttpResponseRedirect [Django-doc] or HttpResponsePermanentRedirect [Django-doc].

It thus combines two layers with each other: the urls layer to calculate the path, and the view layer to construct a HTTP response, that is why it is defined in the django.shortcuts module [Django-doc].

Upvotes: 4

Related Questions