36

When using method-based view, redirecting with reverse didn't complain about this and can still find the root url conf. But, in class-based views, it complain:

ImproperlyConfigured at /blog/new-post/

The included urlconf 'blog.urls' does not appear to have any
patterns in it. If you see valid patterns in the file then the
issue is probably caused by a circular import.

My class is defined like this:

class BlogCreateView(generic.CreateView):
    form_class = Blog
    template_name = 'blog/new-post.html'
    success_url = reverse('blog:list-post')

How to properly use reverse for success_url in class-based views? Thanks.

PS: And I'm interested in why it's need to restart runserver after this error (not like an error like TemplateDoesNotExists which is no need to restart runserver)

2 Answers 2

79

Using reverse in your method works because reverse is called when the view is run.

def my_view(request):
    url = reverse('blog:list-post')
    ...

If you overrride get_success_url, then you can still use reverse, because get_success_url calls reverse when the view is run.

class BlogCreateView(generic.CreateView):
    ...
    def get_success_url(self):
        return reverse('blog:list-post')

However, you can't use reverse with success_url, because then reverse is called when the module is imported, before the urls have been loaded.

Overriding get_success_url is one option, but the easiest fix is to use reverse_lazy instead of reverse.

from django.urls import reverse_lazy
# from django.core.urlresolvers import reverse_lazy  # old import for Django < 1.10

class BlogCreateView(generic.CreateView):
    ...
    success_url = reverse_lazy('blog:list-post')

To answer your final question about restarting runserver, the ImproperlyConfigured error is different from TemplateDoesNotExists because it occurs when the Django application is loaded.

1
  • reverse_lazy() works fine with Django 1.9, I have tried, reverse() throws an exception.
    – hygull
    Jan 30, 2019 at 6:09
15

Try using reverse_lazy instead of reverse in your CBV. Its a lazily evaluated version of reverse. It won't execute until the value is needed.

from django.core.urlresolvers import reverse_lazy

class BlogCreateView(generic.CreateView):
    form_class = Blog
    template_name = 'blog/new-post.html'
    success_url = reverse_lazy('blog:list-post')
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.