over 8 years ago

I had the following code:

from django.core.urlresolvers import reverse

class UserProfileView(FormView):
    template_name = 'profile.html'
    form_class = UserProfileForm
    success_url = reverse('index')

When the code above runs, an error is thrown:

django.core.exceptions.ImproperlyConfigured: The included urlconf 'config.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.

There are two solutions to this problem, solution one:

from django.core.urlresolvers import reverse_lazy 

class UserProfileView(FormView):
    template_name = 'profile.html'
    form_class = UserProfileForm
    success_url = reverse_lazy('index') # use reverse_lazy instead of reverse

Solution 2:

from django.core.urlresolvers import reverse

class UserProfileView(FormView):
    template_name = 'profile.html'
    form_class = UserProfileForm
    
    def get_success_url(self): # override this function if you want to use reverse

        return reverse('index')

According to Django's document, reverse_lazy should be used instead of reverse when your project's URLConf is not loaded. The documentation specifically points out that reverse_lazy should be used in the following situation:

  • providing a reversed URL as the url attribute of a generic class-based view. (this is the situation I encountered)

  • providing a reversed URL to a decorator (such as the login_url argument for the django.contrib.auth.decorators.permission_required() decorator).

  • providing a reversed URL as a default value for a parameter in a function’s signature.

It is unclear when URLConf is loaded. At least I cannot find the documentation on this topic. So if the above error occurs again, try reverse_lazy

← Django create a radio input using Bootstrap3's inline style 如何在Mac上安装Ruby和rbenv →
 
comments powered by Disqus