Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse for success_url on Django Class Based View complain about circular import

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)

like image 385
Mas Bagol Avatar asked Jul 07 '15 17:07

Mas Bagol


1 Answers

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.

like image 156
Alasdair Avatar answered Sep 20 '22 11:09

Alasdair