ImportError at/ No module name <appname>

2,806 views
Skip to first unread message

djangobie

unread,
Dec 20, 2012, 8:27:42 AM12/20/12
to django...@googlegroups.com
Hi, I have just started practicing a tutorial for buidling a  basic blog ( http://www.djangorocks.com/tutorials/how-to-create-a-basic-blog-in-django/starting-your-application.html )

Did exactly the same (except, using 'djangopractice' as project name instead of 'djangorocks')
Actually It also did run twice, but than started showing ImportError.

My files:
--------------------
**settings.py**
--------------------
# Django settings for djangopractice project.
#import os, django
#DJANGO_ROOT = os.path.dirname(os.path.realpath(django.__file__))
#SITE_ROOT = os.path.dirname(os.path.realpath('__file__'))

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_...@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'djangopractice',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': '1290',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Asia/Karachi'

# Language code for this installation. All choices can be found here:
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '@io!2+0*rw1o0tjq%t5zb8e$v(wf3p#yk_8#lb^%hrerzijwt1'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'djangopractice.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'djangopractice.wsgi.application'

TEMPLATE_DIRS = (
    "/home/username/djangosites/djangopractice/Templates"
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',    
    'django.contrib.admin',
    'django.contrib.admindocs',
    'blog',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

--------------
**urls.py**
--------------
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('',
    (r'^$', 'djangopractice.blog.views.index'),
    url(
r'^blog/view/(?P<slug>[^\.]+).html',
'djangopractice.blog.views.view_post', name='view_blog_post'),
    url(
r'^blog/category/(?P<slug>[^\.]+).html',
'djangopractice.blog.views.view_category',
name='view_blog_category'),
    
    # Examples:
    # url(r'^$', 'djangopractice.views.home', name='home'),
    # url(r'^djangopractice/', include('djangopractice.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)),
)

----------------
**views.py**
----------------
from blog.models import Blog, Category
from django.shortcuts import render_to_response, get_object_or_404

def index(request):
    return render_to_response('index.html', {
'category': Category.objects.all(),
'posts': Blog.objects.all()[:5]
    })

def view_post(request, slug): #slug is mapped to, from the urls.py
    return render_to_respomse('view_post.html', {
'post': get_object_or_404(Blog, slug=slug)
    })

def view_category(request, slug):
    category = get_object_or_404(Category, slug=slug)
    return render_to_response('view_category.html' {
'category':category, 
'posts': Blog.objects.filter(category=category)[:5]
})

--------------------
**models.py**
-------------------
from django.db import models
from django.db.models import permalink

class Blog(models.Model):
    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    body = models.TextField()
    posted = models.DateField(db_index=True, auto_now_add=True)
    category = models.ForeignKey('blog.Category')

    def __unicode__(self):
        return '%s' % self.title

    @permalink
    def get_absolute_url(self): #returns a url automatically calculating, based on urls.py param
return ('view_blog_post', None, { 'slug': self.slug})

class Category(models.Model):
    title = models.CharField(max_length=100, db_index=True)
    slug = models.SlugField(max_length=100, db_index=True)

    def __unicode__(self):
        return '%s' % self.title

    @permalink
    def get_absolute_url(self):
        return ('view_blog_category', None, { 'slug': self.slug})

------------------
**admin.py**
------------------
from django.contrib import admin
from blog.models import Blog, Category

#class BlogAdmin(admin.ModelAdmin):
#    exclude = ['posted']
#    prepopulated_fields = {'slug': ('title',)}

#class CategoryAdmin(admin.ModelAdmin):
#    prepopulated_fields = {'slug': ('title',)}

#admin.site.register(Blog, BlogAdmin)
#admin.site.register(Category, CategoryAdmin)


admin.site.register(Blog)
admin.site.register(Category)

----------------------
python manage.py validate
0 errors 
also syncbd properly... but don't why not considering my app a modeule.

my dir structure is:
----------------------------------------------------------------------
djangopractice-
                     --djangopractice-
                                           - __init__.py
                                           - settings.py
                                           - urls.py
                                           - wsgi.py
                    
                     --blog-
                                           - models.py
                                           - views.py
                                           - admin.py
                                           - __init__.py
                                           - test.py

                     --Templates-
                                          - base.html
                                          - index.html
                                          - view_category.html
                                          - view_posts.html
-------------------------------------------------------------------------

Exact error I am getting in the browser is: 
------------------------------------------------------

ImportError at /

No module named blog
Request Method:GET
Request URL:http://localhost:8000/
Django Version:1.4.3
Exception Type:ImportError
Exception Value:
No module named blog
Exception Location:/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py in import_module, line 35
Python Executable:/usr/bin/python
Python Version:2.7.3
Python Path:
['/home/username/djangosites/djangopractice',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PIL',
 '/usr/lib/python2.7/dist-packages/gst-0.10',
 '/usr/lib/python2.7/dist-packages/gtk-2.0',
 '/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
 '/usr/lib/python2.7/dist-packages/ubuntuone-client',
 '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel',
 '/usr/lib/python2.7/dist-packages/ubuntuone-couch',
 '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']

-----------------------------

Thanks

djangobie

unread,
Dec 20, 2012, 11:55:22 PM12/20/12
to django...@googlegroups.com
Can someone kindly look into this.

Peter of the Norse

unread,
Dec 24, 2012, 7:05:43 PM12/24/12
to django...@googlegroups.com
The error is pretty clear: It can't find /home/username/djangosites/djangopractice/blog/__init__.py Make sure that file exists. Try running `manage.py shell` and `import blog`. Also, make sure that the files are readable by your web server, e.g. apache.
Peter of the Norse



Ryan Blunden

unread,
Dec 25, 2012, 1:11:12 AM12/25/12
to django...@googlegroups.com
Did this fix the problem for you?

Did you create the application using `python manage.py startapp blog`? If so, that would've created the blog application as a Python module. The __init__.py is required so Python knows to treat the directory containing the __int__.py as a module.

You can also run `python manage.py validate` when debugging these sort of issues instead of running the local server as a faster feedback loop.

Let us know how you go.

Cheers,
Ryan
<font color=...
Show original

djangobie

unread,
Dec 25, 2012, 7:29:22 AM12/25/12
to django...@googlegroups.com
I appreciate your response.
The __init__.py is there in the app folder (yes, I created the app via manage.py).
It ran perfectly on initial attempts, but with new code added, I got stuck. My so far conclusion (though, not helping at all) is may be I have set some kind 'circular loop' here, while loading (importing) modules, that's why I have pasted all the code from almost all the files.

Thanks
<font color="#222...
Show original

donarb

unread,
Dec 25, 2012, 1:16:23 PM12/25/12
to django...@googlegroups.com
On Tuesday, December 25, 2012 4:29:22 AM UTC-8, djangobie wrote:
I appreciate your response.
The __init__.py is there in the app folder (yes, I created the app via manage.py).
It ran perfectly on initial attempts, but with new code added, I got stuck. My so far conclusion (though, not helping at all) is may be I have set some kind 'circular loop' here, while loading (importing) modules, that's why I have pasted all the code from almost all the files.

In your urls.py, remove the 'djangopractice' from the view paths. Most likely, the tutorial was written using 1.3. so for the first path, it should be:

url(r'^$', 'blog.views.index'),


Pranay Shah

unread,
Aug 11, 2013, 8:11:11 PM8/11/13
to django...@googlegroups.com
I just want to thank everyone. I had an error "no module name image" since yesterday nite. I googled and found out that I need to install python image library. I did that. I still continued getting error. Just then I came across this post where someone was getting "no module... blog". I read it and found out the prob. Initially I had an "image" view which I deleted last nite as I was no longer gonna use it. But I didnt remove its mapping form the urls.py. I commented the lines for image - views and it worked.

Thank you all. Now I shall start working on the actual stuff which I was supposed to work from last nite. Its actually my internship homework.

Thank you once again. 

Scott Anderson

unread,
Nov 7, 2015, 12:19:24 PM11/7/15
to Django users
We just tripped across something similar here as well. The person doing the tutorial had flipped the 'startup' and 'put "blog" in the INSTALLED_APPS' steps of the tutorial. She commented out 'blog' from INSTALLED_APPS and startapp worked as intended.

-scott

Aravind S

unread,
Oct 1, 2016, 1:16:37 PM10/1/16
to Django users
Reply all
Reply to author
Forward
0 new messages