Hello there!
The reverse function is normally used for deriving urls simply by referencing the url’s name.
If those urls have any parameters to them, we can pass them to reverse.
However, in its current state, reverse does not on its own encode the parameters. This means it may in some cases provide you with unusable urls.
I propose some change on how this is handled. Below are some ideas i have for this change. Please note that when i refer to the “user” i mean the developer which is building an application using Django. I am not referring to the administrator or any end-user which may run or use a project.
Why change the behaviour at all?
I’m not saying everyone is going to benefit from this change, users may actually not have noticed that they should (or even need to) encode their parameters, not all url parameters are created equal. When you only ever generate urls with integer based primary keys or slug-ified strings, this is pretty much a non issue.
My issue is that the problem may actually never come up in testing:
It may only show itself once deployed and in production. When not encoding the input properly, we generate useless url’s for seemingly no reason. Django already takes care of decoding the client’s requested url address. Its clear that when i call reverse, that i want a url pointing to a urlpattern/view. No matter what arguments/values i passed (as long as the mandatory ones are present).
Different approaches and problems
Default encoding
If the default behavior is to properly encode all parameters for the url, old code may break as the encoding was previously handled by the user.
To combat the breaking API change, view the section “Optional encoding”.
Optional encoding
Give the user a simple boolean argument for reverse, set to False by default.
This doesn’t break the API and gives users an easy way to make sure they are generating valid urls. No matter the value(s) passed.
However, this isn’t perfect either. The user has to be aware of this functionality, and actually use it. Encoding parameters properly is a rather simple to do, so it may actually sit unused, even in cases where it shouldn’t.
This could also later on be changed to a breaking change by changing the default value of our argument.
Documentation!
Instead of changing the implementation, it should be clearly communicated that reverse does not handle encoding its parameters and not doing it may result in broken urls.
By far the simplest approach, but we aren’t doing anything for already existing implementations.
Should reverse be changed? What do you think?
Best regards
JaK