Question

I have the following urls.py file:

from django.conf.urls import patterns, url
from base import views

urlpatterns = patterns('',
    url(r'^$', 'views.index', name='index'),
    url(r'^item/new', 'views.newItem', name='newItem'),
    url(r'^item/submitted', 'views.itemSubmitted', name='itemSubmitted'),
)

This doesnt work, it gives me an ImportError message saying that there is no module named views. When i remove the second import line above and change the lines from views.viewname to base.views.viewname it works. Does someone know why the import is not working?

Was it helpful?

Solution

Your url route list statement is using string statements to define the location of the views. Django will attempt to lazy-load view methods when required, which can be great for strange situations where importing the view methods would cause import loops. If import loops aren't a problem (which they shouldn't be), you have two ways of doing this:

from django.conf.urls import patterns, url
from base import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^item/new', views.newItem, name='newItem'),
    url(r'^item/submitted', views.itemSubmitted, name='itemSubmitted'),
)

or

from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^$', 'base.views.index', name='index'),
    url(r'^item/new', 'base.views.newItem', name='newItem'),
    url(r'^item/submitted', 'base.views.itemSubmitted', name='itemSubmitted'),
)

In the former, you are passing the view method as a property for the route. In the latter, you are passing an import path to the view methods. Note that in the latter you do not need to provide an import statement for the view.

To cut down on repitition, you can also extract the repeated prefix 'base.views':

from django.conf.urls import patterns, url

urlpatterns = patterns('base.views',
    url(r'^$', 'index', name='index'),
    url(r'^item/new', 'newItem', name='newItem'),
    url(r'^item/submitted', 'itemSubmitted', name='itemSubmitted'),
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top