Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Import views from separate apps

Tags:

python

django

I'm new to Django and working my way through "The Django Book" by Holovaty and Kaplan-Moss. I have a project called "mysite" that contains two applications called "books" and "contact." Each has its own view.py file. In my urls.py file I have the following:

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

When I run my code I get this error:

NameError at /search/ ... Exception value: 'module' object has no attribute 'search'

What I believe is happening is that since views from contact was imported last, Django is looking at contact's view which does not contain search (search is in books' view).

What is the proper way to import the views.py file from two distinct applications within a Django urls file?

Thanks for your help!

like image 324
Jim Avatar asked Jul 11 '12 18:07

Jim


People also ask

How will you import views in Django?

from django.shortcuts import render # Create your views here. Find it and open it, and replace the content with this: members/views.py : from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello world!")

Can we create multiple views in Django?

Yes, this works not only for views.py but also for models.by or tests.py .

Which are the two basic categories of views in Django?

Django has two types of views; function-based views (FBVs), and class-based views (CBVs).


2 Answers

Disclaimer: Not a Django answer

The problem is with these two lines:

from books import views
from contact import views

The second import is shadowing the first one, so when you use views later you're only using the views from contact.

One solution might be to just:

import books
import contact

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

I'm not sure, but I also think that you don't actually need to import anything and can just use strings in your pattern, something like: 'books.views.search'.


Another possiblity is to follow Simon Visser suggestion:

from books.views import search
from contact.views import contact
like image 78
Rik Poggi Avatar answered Sep 29 '22 12:09

Rik Poggi


from books import views
from contact import views

You are overwriting the name views. You need to import them as different names or as absolute names.

import books.views
import contact.views

... or ...

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

Then use the correct name when defining your URLs. (books.views.search or books_views.search depending on the method you choose)

like image 28
FogleBird Avatar answered Sep 29 '22 12:09

FogleBird