I'm Working through "The Django Book" and I keep getting the error "cannot import name current_datetime"
Urls.py:
from django.conf.urls.defaults import patterns, include, url
from mysite.views import current_datetime, hello
urlpatterns = patterns('',
('^hello/$', hello),
('^time/$', current_datetime),
(r'^time/plus/(\d{1,2})/$', hours_ahead),
)
My Views.py:
from django.http import HttpResponse
import datetime
def hello(request):
return HttpResponse("Hello world")
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
My working directory:
./mysite:
__init__.py manage.py mysite views.py
No matter what I do, I get the same import error in urls.py line 2, regarding current_time:
Environment:
Request Method: GET
Request URL: http://localhost:8000/
Django Version: 1.5.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
103. resolver_match = resolver.resolve(request.path_info)
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in resolve
319. for pattern in self.url_patterns:
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in url_patterns
347. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in urlconf_module
342. self._urlconf_module = import_module(self.urlconf_name)
File "/Library/Python/2.7/site-packages/django/utils/importlib.py" in import_module
35. __import__(name)
File "/Users/jvieitez/Code/djcode/mysite/mysite/urls.py" in <module>
2. from mysite.views import hello, current_datetime, hours_ahead
Exception Type: ImportError at /
Exception Value: cannot import name current_datetime
Something is wrong with your working directory. manage.py and views.py should not be in the same directory. I would recommend renaming the inner mysite to something else, so you avoid the confusion, and views.py should be in the inner mysite directory. You said
from mysite.views import current_datetime, hello
but views.py isn't in the mysite directory. That's the problem.
Related
I'm using django framework and I'm experiencing an error.
this is my settings.py, INSTALLED_APPS
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps',
)
and, this is my apps/ directory.
apps/
__init__.py
qnaBoard/
admin.py
migrations/
tests.py
views.py
urls.py
__init__.py
models.py
urls.py
and, this is my urls.py, which is located in the same directory with settings.py.
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^course/', include('apps.qnaBoard.urls')),
url(r'^admin/', include(admin.site.urls)),
)
I think I followed the right way, but, it says it cannot find apps.qnaBoard.urls, and raises syntax error.
This is traceback :
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
98. resolver_match = resolver.resolve(request.path_info)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve
343. for pattern in self.url_patterns:
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in url_patterns
372. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in urlconf_module
366. self._urlconf_module = import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py" in import_module
37. __import__(name)
File "/root/campusmate/campusmate/campusmate/urls.py" in <module>
9. url(r'^course/', include('apps.qnaBoard.urls')), #need to apply course router
File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py" in include
28. urlconf_module = import_module(urlconf_module)
File "/usr/lib/python2.7/importlib/__init__.py" in import_module
37. __import__(name)
Exception Type: SyntaxError at /course/
Exception Value: invalid syntax (urls.py, line 4)
and this is apps/qnaBoard/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from apps.qnaBoard.views import showPost
from apps.qnaBoard.views import showQuestionThread
from apps.qnaBoard.views import writeReply
from apps.qnaBoard.views import writeQuestion
from apps.qnaBoard.views.import writeAnswer
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'campusmate.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
# need to be refactored when course router are attached.
url(r'^([0-9]+)/([1-4])/([A-Za-z0-9]+)/article/list/', showPost.as_view()),
url(r'^([0-9]+)/([1-4])/([A-Za-z0-9]+)/article/([0-9]+)/$', showQuestionThread.as_view()),
url(r'^([0-9]+)/([1-4])/([A-Za-z0-9]+)/article/([0-9]+)/reply', writeReply.as_view()),
url(r'^([0-9]+)/([1-4])/([A-Za-z0-9]+)/article/write/$', writeQuestion.as_view()),
url(r'^([0-9]+)/([1-4])/([A-Za-z0-9]+)/article/write/([0-9]+)/$', writeAnswer.as_view()),
)
remove . from urls.
Problem was in following file:
File name: apps/qnaBoard/urls.py
from apps.qnaBoard.views.import writeAnswer the . is there, remove it.
I'm trying to merge an existing Django app with an existing Django framework. This is causing some problems, as they were developed using different python/Django versions, but I'm getting on pretty well.
I'm running into a bug I can't seem to wrap my head around now though. I'm convinced I'm doing something wrong in the urls.py files, but I can't seem to figure out what exactly.
So, here's the error I'm getting:
Environment:
Request Method: GET
Request URL: http://localhost:8000/
Django Version: 1.6.4
Python Version: 3.4.0
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'kapstok',
'forecast',
'prefscan.survey',
'prefscan.ipblocker',
'prefscan.util',
'prefscan.controlcenter')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/usr/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
101. resolver_match = resolver.resolve(request.path_info)
File "/usr/lib/python3.4/site-packages/django/core/urlresolvers.py" in resolve
337. for pattern in self.url_patterns:
File "/usr/lib/python3.4/site-packages/django/core/urlresolvers.py" in url_patterns
365. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/lib/python3.4/site-packages/django/core/urlresolvers.py" in urlconf_module
360. self._urlconf_module = import_module(self.urlconf_name)
File "/usr/lib/python3.4/importlib/__init__.py" in import_module
104. return _bootstrap._gcd_import(name[level:], package, level)
File "/home/linus/fo/web-framework/pi/urls.py" in <module>
13. url(r'^prefscan/', include('prefscan.urls', namespace="prefscan")),
File "/usr/lib/python3.4/site-packages/django/conf/urls/__init__.py" in include
26. urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.4/importlib/__init__.py" in import_module
104. return _bootstrap._gcd_import(name[level:], package, level)
File "/home/linus/fo/web-framework/prefscan/urls.py" in <module>
56. add_to_builtins('util.templatetags.closure_extras')
File "/usr/lib/python3.4/site-packages/django/template/base.py" in add_to_builtins
1331. builtins.append(import_library(module))
File "/usr/lib/python3.4/site-packages/django/template/base.py" in import_library
1263. if is_library_missing(taglib_module):
File "/usr/lib/python3.4/site-packages/django/template/base.py" in is_library_missing
1247. return is_library_missing(path)
File "/usr/lib/python3.4/site-packages/django/template/base.py" in is_library_missing
1247. return is_library_missing(path)
File "/usr/lib/python3.4/site-packages/django/template/base.py" in is_library_missing
1242. path, module = name.rsplit('.', 1)
Exception Type: ValueError at /
Exception Value: need more than 1 value to unpack
Which seems to point to the pi/urls.py file. This file looks like:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pi.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^', include('kapstok.urls', namespace="kapstok")),
url(r'^admin/', include(admin.site.urls)),
url(r'^prefscan/', include('prefscan.urls', namespace="prefscan")),
)
Whenever I comment out the line url(r'^prefscan/', ...), the error goes away.
prefscan/urls.py looks like this:
import django
if django.VERSION < (1, 6):
from django.conf.urls.defaults import patterns, include, url
else:
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.template.loader import add_to_builtins
import prefscan.controlcenter.urls
import prefscan.ipblocker.core
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^prefscan/$', 'survey.views.login'),
url(r'^prefscan/cc/staff/siteadmin/', include(admin.site.urls)),
url(r'^prefscan/cc/' , include(prefscan.controlcenter.urls.urlpatterns)),
url(r'^prefscan/survey/login/$', 'survey.views.login'),
url(r'^prefscan/survey/logout/$', 'survey.views.logout'),
url(r'^prefscan/language/(?P<language>[a-z]+)/$', 'survey.views.set_preferred_language'),
url(r'^prefscan/survey/$', 'survey.views.choose'),
url(r'^prefscan/survey/questionnaire/(?P<survey_id>\d+)/$','survey.views.questionnaire'),
url(r'^prefscan/survey/(?P<survey_id>\d+)/$', 'survey.views.detail'),
url(r'^prefscan/survey/pdf/(?P<survey_id>\d+)/$', 'survey.views.response_pdf'),
url(r'^prefscan/survey/json/(?P<survey_id>\d+)/$', 'survey.views.json_get_assignment'),
url(r'^prefscan/survey/json/list$', 'survey.views.json_list_surveys'),
url(r'^prefscan/survey/json/cards/(?P<survey_id>\d+)/$', 'survey.views.json_list_cards'),
url(r'^prefscan/survey/json/shape/(?P<survey_id>\d+)/$', 'survey.views.json_list_shape'),
url(r'^prefscan/survey/json/savequest/(?P<survey_id>\d+)/$','survey.views.json_store_questionnaire'),
url(r'^prefscan/survey/json/store/(?P<survey_id>\d+)/$', 'survey.views.json_store_assignment'),
url(r'^prefscan/survey/json/load/(?P<survey_id>\d+)/$', 'survey.views.json_load_assignment'),
url(r'^prefscan/survey/json/send/(?P<survey_id>\d+)/$', 'survey.views.json_send_response'),
url(r'^prefscan/survey/keepalive/$', 'survey.views.keep_alive'),
)
urlpatterns += staticfiles_urlpatterns()
js_info_dict = {
'domain': 'djangojs',
'packages': ('js'),
}
urlpatterns += patterns('',
(r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
)
urlpatterns += prefscan.ipblocker.core.urlpatterns
add_to_builtins('util.templatetags.closure_extras')
add_to_builtins('django.templatetags.i18n')
I'm just not seeing what's going wrong! The prefscan line seems identical to the kapstok line, which works without hiccups.
I have run into an issue while working through the Django tutorial, specifically when adding more views to the poll application. For reference, this is the beginning of the section that trips me up: https://docs.djangoproject.com/en/1.5/intro/tutorial03/#writing-more-views
Prior to that section, I can get the polls/ view to show up with no issue. But when I add three additional views to make polls/views.py look like this:
def detail(request, poll_id):
return HttpResponse("You're looking at poll %s." % poll_id)
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request, poll_id):
return HttpResponse("You're voting on poll %s." % poll_id)
and then make polls/urls.py look like this:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
I get an error. As an aside, my mysite ROOT_URLCONF is pointing to mysite/urls.py which looks like this:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
)
The error that I am getting is:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/34
Django Version: 1.5.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'polls')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/home/matthew/.virtualenvs/djangopoll/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
92. response = middleware_method(request)
File "/home/matthew/.virtualenvs/djangopoll/local/lib/python2.7/site-packages/django/middleware/common.py" in process_request
69. if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
File "/home/matthew/.virtualenvs/djangopoll/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in is_valid_path
551. resolve(path, urlconf)
File "/home/matthew/.virtualenvs/djangopoll/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
440. return get_resolver(urlconf).resolve(path)
File "/home/matthew/.virtualenvs/djangopoll/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
319. for pattern in self.url_patterns:
File "/home/matthew/.virtualenvs/djangopoll/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in url_patterns
347. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/matthew/.virtualenvs/djangopoll/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in urlconf_module
342. self._urlconf_module = import_module(self.urlconf_name)
File "/home/matthew/.virtualenvs/djangopoll/local/lib/python2.7/site-packages/django/utils/importlib.py" in import_module
35. __import__(name)
File "/home/matthew/djangopoll/mysite/mysite/urls.py" in <module>
8. url(r'^polls/', include('polls.urls')),
File "/home/matthew/.virtualenvs/djangopoll/local/lib/python2.7/site-packages/django/conf/urls/__init__.py" in include
25. urlconf_module = import_module(urlconf_module)
File "/home/matthew/.virtualenvs/djangopoll/local/lib/python2.7/site-packages/django/utils/importlib.py" in import_module
35. __import__(name)
Exception Type: SyntaxError at /polls/34
Exception Value: invalid syntax (urls.py, line 9)
Also, the following may be informative:
Using Django 1.5
Using Python 2.7.3
Using Django 1.5 documentation
Using VirtualBox
Using VirtualEnv
Any help is appreciated! Why am I getting this error?
Looks like Python cannot import polls.urls - that's why __import__(name) fails. The "name" here would be your module name, 'polls.urls'.
To find out why the system cannot import your polls.urls, try importing it interactively.
$ python manage.py shell
Python ... blah blah
...
> import polls.urls
This will fail, but the traceback will give you the next clue to where your error is.
Good luck!
I am getting the error
ViewDoesNotExist at /
Could not import blog.views. View does not exist in module blog.
With Django
My URLS file looks like this
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'blog.views.home', name='home'),
# url(r'^Blog/', include('Blog.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
and my directory tree looks like this
Blog
_manage.py
_Blog
__wsgi.py
__urls.py
__settings.py
__ __init__.py
_blog
__views.py
__tests.py
__Templates
____index.html
__models.py
__ __init__.py
And in the views.py
from django.shortcuts import render_to_response
from blog.models import posts
def home(request):
return render_to_response('index.html')
Further Debugging:
Environment:
Request Method: GET
Request URL: http://192.168.2.3:1337/
Django Version: 1.4.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
101. request.path_info)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve
300. sub_match = pattern.resolve(new_path)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve
209. return ResolverMatch(self.callback, args, kwargs, self.name)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in callback
216. self._callback = get_callable(self._callback_str)
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py" in wrapper
27. result = func(*args)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in get_callable
101. (lookup_view, mod_name))
Exception Type: ViewDoesNotExist at /
Exception Value: Could not import blog.views. View does not exist in module blog.
Based on your debugging output it seems that the blog application isn't present in your INSTALLED_APPS setting in settings.py
Apparently you forgot include your 'blog' application into django installed applications on settings.py
Check capitalization in your naming and also make sure you have an init.py in your app.
I am getting the error
Exception Value:No module named index. i have __init__.py in DjangoPhoneBook and phonebook folder. I'm newbie to django and i m following the tutorial on djangoproject website. I have googled this error but not getting any solutions.
What is cause and solution to this problem??
Environment:
Request Method: GET
Request URL: http://localhost:8000/Book/
Django Version: 1.2.3
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'phonebook',
'django.contrib.admin']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response
91. request.path_info)
File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in resolve
217. sub_match = pattern.resolve(new_path)
File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in resolve
215. for pattern in self.url_patterns:
File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in _get_url_patterns
244. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/lib/pymodules/python2.6/django/core/urlresolvers.py" in _get_urlconf_module
239. self._urlconf_module = import_module(self.urlconf_name)
File "/usr/lib/pymodules/python2.6/django/utils/importlib.py" in import_module
35. __import__(name)
Exception Type: ImportError at /Book/
Exception Value: No module named index
Contents of urls.py is
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
from DjangoPhoneBook.phonebook.views import *
urlpatterns = patterns('',
(r'^Book/$', include('index'))
(r'^admin/', include(admin.site.urls)),
)
and of views.py is
from django.http import HttpResponse
def index(request):
return HttpResponse("This is a view page")
Remove the include from your first line. include is the syntax for adding a separate url conf, so python is looking for a module called index.
Change it to the full python dot path to your view function.
urlpatterns = patterns('',
(r'^Book/$', 'path.to.my.views.index'), # <-- and add a comma here
(r'^admin/', include(admin.site.urls)),
)
edit: I notice you are importing your view functions. You can also specify the view function itself
urlpatterns = patterns('',
(r'^Book/$', index),
(r'^admin/', include(admin.site.urls)),
)