When I read Django code sometimes, I see in some templates reverse(). I am not quite sure what this is but it is used together with HttpResponseRedirect. How and when is this reverse() supposed to be used?
When I read Django code sometimes, I see in some templates reverse() . I
Share
reverse()| Django documentationLet’s suppose that in your
urls.pyyou have defined this:In a template you can then refer to this url as:
This will be rendered as:
Now say you want to do something similar in your
views.py– e.g. you are handling some other URL (not/foo/) in some other view (notsome_view) and you want to redirect the user to/foo/(often the case on successful form submission).You could just do:
But what if you want to change the URL in the future? You’d have to update your
urls.pyand all references to it in your code. This violates the DRY (Don’t Repeat Yourself) principle and the whole idea of editing in one place only – which is something to strive for.Instead, you can say:
This looks through all URLs defined in your project for the URL defined with the name
url_nameand returns the actual URL/foo/.This means that you refer to the URL only by its
nameattribute – if you want to change the URL itself or the view it refers to you can do this by editing one place only –urls.py.