[Django]-Reverse for success_url on Django Class Based View complain about circular import

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.

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')

Leave a comment