Django cannot import app - python

Following the django-rest tutorial
app/urls.py:
from django.conf.urls import url, include
from rest_framework import routers
from app.abbr import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
Directory structure:
Error:
File "..../app/app/urls.py", line 3, in
from app.abbr import views
ImportError: No module named 'app.abbr'
So, sigh...

It would have been useful if you pointed to the tutorial that showed you to do this.
You should not import from app; that refers to the inner directory containing your urls.py. Just import from abbr.
from abbr import views

And what if you change import like this?
from app.app.abbr import views?

I am considering that you are using django 1.9 +
Try this
from . import views

The root directory folder named App in your case is named after your project name by default when you start a new project via the django-admin startproject command.
you can rename your root directory folder to whatever you want and it won't affect your project.
when in your code are importing from app, it is actually looking inside the 'app' folder containig the 'settings.py' file.
the django-rest tutorial you are following contains an error when they are doing from tutorial.quickstart import views which should be from quickstart import views
so the same goes for you, you should do from abbr import views

Related

importing apps into urls.py

I am trying to import views from my apps into the urls.py file. For awhile, I was able to using "from app_name.views import view_name", but for some reason now it is not recognizing the app name.
I did not change anything in my settings.py file so I'm not sure what caused this. I did delete some migrations and an my database.
One thing that is weird is that I can import them if I go up a folder so, "from src.appname.views" and this seems to work, but is not what I want since by base directory is the src folder.
from django.contrib import admin
from django.urls import path
from pages.views import home_page, history, more_information, prop_analysis
from Product.views import property_analysis_tools, property_analysis_results
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_page),
path('home', home_page),
path('history', history),
path('information', more_information),
path('analyze', prop_analysis),
path('results', property_analysis_results)
Another odd thing is that when I run the server, all of these views seem to work. Can Django sometimes give off false errors?
In Django in order to import an app.view into project urls, we create an additional urls.py in every app and link that urls.py into
our project urls.py , just as shown below
change project urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('pages.urls', namespace="pages")),
]
create another urls.py in your pages app
as below, similarly in any other apps.
from django.urls import path
from .views import (home_page,history,....)
app_name = 'pages'
urlpatterns = [
path(' ', homepage , name='homepage-view'),
path('history/',history, name='history-view'),
]
Every other view from respective app.views will be included in corresponding app.urls [if u have multiple apps]
nB: changes may occur according to your settings.py configurations,
for more, read this django URL documentation
watch Corey Schafer playlist best Django tutorial for beginners

ModuleNotFoundError: No module named 'src'

I'm changing view of homepage with app names pages.
I've added pages to settings. this is how directory look like:
- trydjango
- src/
- pages/
- __init__
- views
- products
- trydjango/
- __init__
- settings
- urls
- manage
views' code:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home_view(*args, **kwargs):
return HttpResponse("<h1>Hello Again</h1>")
urls code
from django.contrib import admin
from django.urls import path
from src.pages.views import home_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view, name='home'),
]
and I see this error when I run server
ModuleNotFoundError: No module named 'src'
First you need to understand what an app in Django is compared to a project.
When you register an app django will look in the project root folder when you try to import it.
Your project root is where your manage.py file is. In your case the src folder.
So when you want to import your views module you need to state
from pages.views
rather than
from src.pages.views
I suggest that you read through and follow (by coding it yourself) the Django tutorial to learn more about project structure and creating your own apps with models, urls etc.
I got the same problem, IDE may use red underline but this code is still correct:
from pages.views

django import error - from . import views in urls under app

I did declare like from . import views in urls.py.
To use TemplateView, this urls.py is needed.
urls.py
from django.urls import path, re_path
from . import views
app_name = 'scheduler'
urlpatterns = [
re_path(r'^service/(?P<status>\w+)', views.SchedulerView.as_view(), name='schedule-service')
]
I think nothing but normal implementation.
Error occurs like the below.
from . import views
ImportError: cannot import name 'views'
Older versions django did work. But it's not working in django 2.0
App Structure
- server
- scheduler
- templatetags
schedule_status.py
urls.py
models.py
views.py
- main
settings.py
urls.py
- manage.py
I just guess 'scheduler' app's path is incorrect to work "from . import views"
Is there anyone who solved or check more things. these problem after django 2.0.
ps. sorry, I forgot to add view.py in structure in question. SchedulerView is declared in views.py
I did found a solution. python 3.6 has changed something.
I did create directory as views and added scheduler_view.py
and
from .views import scheduler_view as view
app_name = 'scheduler'
urlpatterns = [
re_path(r'^service/(?P<status>\w+)', view.SchedulerView.as_view(), name='schedule-service')
]
it doesn't occur error and runserver as well.
plus I did error occur again in another file. it's for older python.
scheduler_view.py
from scheduler import Scheduler -> from scheduler.scheduler import Scheduler
I did change it.
http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html
I wish it's helpful.

Django: Order of imports means only one views.py files is accessable

I'm just working through the DjangoBook Chapter7 tutorial on creating forms.
My issue is that I can only import one views.py file from either my books or contact directories. As a result I am only able to see the pages created by whichever views.py file is imported at the time.
I believe I need someway of differentiating between the two directories so that Django does not get confused (due to my likely bad implementation). I have also included an image of my project directory which might be useful to understand the problem.
Contact import working
from mysite.views import hello, current_datetime, hours_ahead, display_meta
from contact import views
#from books import views
urlpatterns = patterns('',
...
#url(r'^search-form/$', views.search_form),
#url(r'^search/$', views.search),
url(r'^contact_form/$', views.contact),
)
Books import working
from mysite.views import hello, current_datetime, hours_ahead, display_meta
#from contact import views
from books import views
urlpatterns = patterns('',
....
url(r'^search-form/$', views.search_form),
url(r'^search/$', views.search),
#url(r'^contact_form/$', views.contact),
)
My Project structure. I am working in Eclipse with Pydev.
Both contact and books import implemented give the below error
AttributeError at /search/
'module' object has no attribute 'search_form'
Any help is as always much appreciated.
you can use an as statement:
from contact import views as contact_views
from books import views as books_views
and the call view:
url(r'^search-form/$', books_views.search_form),
url(r'^search/$', books_views.search),
url(r'^contact_form/$', contact_views.contact),
You should put the urls.py in your application, as detailed in part 3 of the tutorial.
In your application directory create a urls.py,
contact
- __init__.py
- views.py
- models.py
- urls.py
books
- __init__.py
- views.py
- models.py
- urls.py
In book/urls.py, add the following:
from django.conf.urls import patterns, url
from .views import search, search_form
urlpatterns = patterns('',
url(r'search-form/$', search_form, name='search_form'),
)
Then in your main urls.py, add the following:
url(r'^books/', include('book.urls')),
Please go through the official tutorial as the django book website is out dated.

Django - Import views from separate apps

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!
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
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)
The reason I’m answering this question is because it was answered years ago and those answers are not correct or useful anymore for newer Django versions, or there is a better practice you should know about.
So, if you have more than one app in your Django project then you should use a new urls.py file for every one of your apps. It means that if you start a new app then you have to manually create a new file called urls.py in the subfolder of your new app. Many beginners first do not understand why this is good, but this is a good practice if you plan creating more apps in one Django project.
When you start a project, the urls.py file automatically created in your project folder, but if you create/start a new app in Django, then it is a good practice if you create a separate urls.py for that app in its own folder. (And that way you will never have the "importing different app's views into urls.py" problem in the first place).
After you created the urls.py file for your app, then you have to include that app’s urls.py file in your project’s urls.py file in the following way:
Let’s see an example when you create a new app called ‘my_new_app’.
This is how your project’s main urls.py file should look like:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^my_new_app/', include('my_new_app.urls')),
]
In your project’s urls.py file you have to import the ‘include’ method, then you can include your my_new_app urls.py file in your project’s main urls.py file. In your my_new_app folder you have to manually create a urls.py file as I stated above. Then you have to use that file for all of your urlpatterns of your my_new_app. Then of course this way it’s going to be automatically included in your project’s main urls.py file.
So this is then how your my_new_app own urls.py file should look like:
from django.conf.urls import url
from my_new_app import views
urlpatterns = [
url(r'^$', views.index, name = "index"),
]
Assuming that you also created a first view called ‘index’ in your ‘my_new_app/views.py file.
my_new_app/views.py file look like this:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello World!")
And you can check your my_new_app in your browser at:
http://localhost:8000/my_new_app
(Of course you can give any url to your my_new_app in your project's urls.py file.)
Now, you can create another app, in your Django project, called my_second_app and you should repeat the above steps for that app too. This way you will not have any problem importing views from different apps into urls.py files. This would be a very basic “good practice solution” for this problem in 2017 in Django 1.11.
The URLconfs documentation gives an example of the same situation
You can skip the imports and separate the urls by app as such:
urlpatterns = patterns('books.views',
(r'^/book/search/$', 'search'), #calls books.views.search
)
urlpatterns += patterns('contact.views', #make note of the '+='
(r'^/contact/search/$', 'search'), #calls contact.views.search
)
Heres the approach i took for different view/API versions:
from django.urls import path
from my_app import views as api_v1
from my_app import views_v2 as api_v2
urlpatterns = [
path('view_one', api_v1.ViewOne.as_view()),
path('view_two', api_v2.ViewTwo.as_view()),
]

Categories

Resources