Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django import views multiple times in urls.py

Tags:

django

In Django, is it not possible to have multiple views imports from the urls.py?

For example, I have the following code in urls.py:

from mysite.books import views
from mysite.contact import views

urlpatterns = patterns('',
    (r'^contact/$', views.contact),
    (r'^search/$', views.search),
)

However, the server displays an error unless I disable one of the couples. So my questions are threefold:

1) Is it not possible to have multiple import views statements? 2) How to get around this? 3) What is best practice for where to put all your views.py? One file? Multiple files? etc.

Thank you.

like image 688
David542 Avatar asked Apr 28 '11 18:04

David542


2 Answers

1) Yes it is.

2)

from mysite.books import views as books_views
from mysite.contact import views as contact_views

urlpatterns = patterns('',
    (r'^contact/$', contact_views.contact),
    (r'^search/$', books_views.search),
)

3) Per Django docs, "This code can live anywhere you want, as long as it’s on your Python path.". I keep all the app views in app/views.py

like image 200
Paolo Avatar answered Nov 04 '22 07:11

Paolo


You can import as many things as you like, but objects have to have unique names for them to be distinguished.

There are a couple of ways of dealing with this. One is to simply import the functions, rather than the module:

from mysite.books.views import books
from mysite.contact.views import contact

This is obviously only good if you only have one or two views in each file. A second option is to import the modules under different names:

from mysite.books import views as books_views
from mysite.contact import views as contact_views

A third option is not to import the views at all, but use strings to refer to them:

urlpatterns = patterns('',
    (r'^contact/$', 'contact.views.contact'),
    (r'^search/$', 'book.views.search'),
)

A fourth is to have separate urls.py for each application, and include the urlconfs in the main urls.py.

like image 44
Daniel Roseman Avatar answered Nov 04 '22 07:11

Daniel Roseman