Using reverse_lazy where reverse would be better

Using reverse(...) is better than using reverse_lazy(...) when the url is being reversed after URLConf has been loaded.

Django looks up the URL name as defined in URLConf to generate the URL. There are times when we want to use a URL before the URLConf has been loaded, such as:

  • Using the URL at module level, such as in a class-based view's success_url
  • Using the URL in a view decorator such as @permission_required('foo.bar', login_url=reverse_lazy(...))
  • Using the URL in a function default keyword argument

If the URLConf has been loaded there is no need to use reverse_lazy(...) - just use reverse(...), becasue doing otherwise adds unecessary complexity.

If we spot this issue in your GitHub pull request we give this advice:

models.pymaintainabilitylow
def my_view(request):
-
    url = reverse_lazy('foo')
+
    url = reverse('foo')

Using reverse(...) is better than using reverse_lazy(...) when the url is being reversed after URLConf has been loaded.

Read more
Protect your pull requests from over 40 types of common Django technical debts with our GitHub code review bot.

Configuring this check

Django Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code reverse-lazy-misuse in your pyproject.toml file.

Read more about configuring Django Doctor.