View Django import several times in urls.py

Is it impossible to import multiple views from urls.py in Django?

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 if I do not disconnect one of the pairs. Therefore, my questions are thrice:

1) Is it impossible to have multiple import representation statements? 2) How to get around this? 3) What is the best practice for posting all your views.py? Single file? Multiple files? and etc.

Thanks.

+4
source share
3 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 if you want it in your Python path." I save all kinds of applications in app/views.py

+15
source

You can import as many things as you want, but objects must have unique names to distinguish them.

There are several ways to deal with this. One of them is just importing functions, not a module:

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

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

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

The third option is not to import the views at all, but to use them for reference:

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

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

+6
source

I think the other option is:

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

as described in djangobook .

+1
source

All Articles