AttributeError: 'module' object has no attribute 'META' in Django Project - python

I am working on a blog in Python-Django. When I run the command "python manage.py runserver" in my project folder, I get following error:
Traceback (most recent call last):
File "manage.py", line 6, in <module>
server = request.META.get('wsgi.file_wrapper', None)
AttributeError: 'module' object has no attribute 'META'
I have not seen this error anywhere. Should I include Meta class in my installed_apps? How do I do it?
Here is my manage.py:
#!/usr/bin/env python
import os
import sys
from django.http import request
server = request.META.get('wsgi.file_wrapper', None)
if server is not None and server.__module__ == 'django.core.servers.basehttp':
print('inside dev')
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dj1.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
and settings.py:
"""
Django settings for dj1 project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '(l8*%h2ids25q=x9qb7%x+(b=$1mm&yg8b5ga^0u2w9*+k%+9-'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'dj1.urls'
WSGI_APPLICATION = 'dj1.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)

This is really a big code bulder.
This piece of code here makes no sense inside the manage.py
from django.http import request
server = request.META.get('wsgi.file_wrapper', None)
if server is not None and server.__module__ == 'django.core.servers.basehttp':
print('inside dev')
Perhaps you copied it from somewhere, and didn't put it where it belongs.
This piece of coude would belong in a view. It will never work inside manage.py, and makes asolutely no sense there.
[EDIT]
ALSO, in a view, you should NOT include the import, or you'll get the same error. That means, don't include this from django.http import request

Related

AUTH_USER_MODEL refers to model 'myapp.EmailUser' that has not been installed

ImproperlyConfigured at /
AUTH_USER_MODEL refers to model 'myapp.EmailUser' that has not been installed
I have created my models in myapp/models/ folder.
EmailUser class exists in the file user.py.
Code in __init__.py in models folder:
from user import *
In myapp __init__.py has the code :
from models import EmailUser
Can someone help me to fix the issue.
When I try to run the django locally with runserver command it is working fine. But when I try to run the same with wsgi I am facing this issue.
Settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'myproject.urls'
WSGI_APPLICATION = 'myproject.wsgi.application'
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.postgresql_psycopg2',
'ENGINE': 'django.db.backends.mysql',
# Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'test', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': 'test',
'PASSWORD': '',
'HOST': 'localhost',
# Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
AUTH_USER_MODEL = 'myapp.EmailUser'
STATIC_URL = '/static/'
wsgi.py
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

A server error occurred. Please contact the administrator

I am developing a web-app in Django (python). It was working fine in last few days, but then i started developing another app using django. Now after switching to that old app development when I am running the server, I am getting an error: "A server error occurred. Please contact the administrator."
The traceback from the terminal:
File "/Users/somdipdey/anaconda/lib/python2.7/wsgiref/handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "/Users/somdipdey/anaconda/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 64, in __call__
return self.application(environ, start_response)
File "/Users/somdipdey/anaconda/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 168, in __call__
self.load_middleware()
File "/Users/somdipdey/anaconda/lib/python2.7/site-packages/django/core/handlers/base.py", line 44, in load_middleware
mw_class = import_string(middleware_path)
File "/Users/somdipdey/anaconda/lib/python2.7/site-packages/django/utils/module_loading.py", line 26, in import_string
module = import_module(module_path)
File "/Users/somdipdey/anaconda/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named security
Settings file:
"""
Django settings for SteanneWebsite project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^ay$t!hm-4fm4!)ppxoc!$j1^p1b&kiv+*s&3eox^k*bh$er^8'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'News',
'Messages',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.admin',
)
ROOT_URLCONF = 'SteanneWebsite.urls'
WSGI_APPLICATION = 'SteanneWebsite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL = '/static/'
#Template Location
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "templates"),
)
The SecurityMiddleware is new in the Django development version, and is not available in the released 1.7. If you really want to use it, you should switch to development head, but I do not recommend running a production site from dev. You should probably just remove the reference to it in the middleware settings.

django nonrel ImportError when running a script

I've configurated a virtual environment for my project, all is working except that when I try to run a script to populate the MongoDB data base. I get a ImportError exception.
I am using django mongodb engine Link and djangotoolbox. I want to run a script to populate my mongo db, however when I run it the following exceptions raised:
This is my project skeleton:
This is my models.py file:
from django.db import models
from djangotoolbox.fields import EmbeddedModelField, ListField
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
pages = ListField(EmbeddedModelField("Page"))
def __unicode__(self):
return self.name
class Page(models.Model):
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __unicode__(self):
return self.titleenter code here
This is my settings.py file:
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from pip.exceptions import BadCommand
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'mw7+iswll+f=a!xg9r+*%v=uyv$r_6lqcf)eb27s!4h_!*&9gt'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rango',
)
MIDDLEWARE_CLASSES = (
'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',
)
ROOT_URLCONF = 'tango_with_django_project.urls'
WSGI_APPLICATION = 'tango_with_django_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': 'tango_with_dj',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
STATIC_PATH = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = (
STATIC_PATH,
)
MEDIA_URL = '/media/'
MEDIA_ROOT
This is my populate script populate.py:
import os
def populate():
python_cat = add_cat('Python')
django_cat = add_cat("Django")
frame_cat = add_cat("Other Frameworks")
# Print out what we have added to the user.
for c in Category.objects.all():
print "Category: "+c.name+" was added!"
def add_cat(name):
c = Category.objects.get_or_create(name=name)[0]
return c
# Start execution here!
if __name__ == '__main__':
print "Starting Rango population script..."
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')
from rango.models import Category
populate()
I don't know why djangotoolbox cannot be reached at the populate main scope if it is imported at models.py scope. What is the problem here?

Django AUTHENTICATION_BACKENDS import error

What is the proper way to import a custom backend in settings.py? I currently have the following in settings.py:
AUTHENTICATION_BACKENDS = ('apps.apployment_site.auth.CustomAuth')
where apployment_site is the app, auth is file name, and CustomAuth is the class name.
In my view, I get: ImportError: a doesn't look like a module path after I run the following code:
from django.contrib.auth import authenticate
from apployment_site import *
authenticate(username="username", password="password")
Here's my full settings.py:
"""Django settings for apployment project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3(a=jr=tfedkqzv3f=495%0$ygxjt332(=n0&h=e2bzh(i#r*j'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apployment_site'
)
MIDDLEWARE_CLASSES = (
'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',
)
AUTHENTICATION_BACKENDS = ('apps.apployment_site.auth.CustomAuth')
ROOT_URLCONF = 'apployment.urls'
WSGI_APPLICATION = 'apployment.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL = '/static/'
make sure it's a tuple:
AUTHENTICATION_BACKENDS = ('apps.apployment_site.auth.CustomAuth',)
note the comma at the end
I don't think you need to actually import it into your view. According to the documentation, Django will go through all your authentication backends when you call authenticate().
Thus, just make sure you have all the authentication backends you want in your settings.py.

Importing modules in Django (newbie)

I'm new to both Python and Django and am struggling with what I'm sure is a very simple thing. I'm using PyCharm as my ide and am attempting to follow quickstart guide [here][1]. I setup a virtual env as per the tutorial.
The project is "DjangoProjectApp" and the app is "Lunch"
With the files shown below and a browser pointed to http://localhost:8000/admin/ I get the error:
ImportError at /admin/
No module named 'DjangoProjects.Lunch'
But if I comment out the second url route in urls.py then it works. What is the correct way for me to import this module? Thanks.
urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'DjangoProjects.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^lunch/$', 'DjangoProjects.Lunch.views.index')
)
views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render_to_response
def index(request):
return render_to_response('index.html')
index.html
hello world!
settings.py
"""
Django settings for DjangoProjects project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'd^d9v4j(1maq-&_8^a+kgicmagxwbv*9m$!2st&vqz$5_h$441'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Lunch',
'django.contrib.admin',
)
MIDDLEWARE_CLASSES = (
'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',
)
ROOT_URLCONF = 'DjangoProjects.urls'
WSGI_APPLICATION = 'DjangoProjects.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL = '/static/'
Replace that line with :
url(r'^lunch/$', 'Lunch.views.index')
There is no need to specify the name of the project. You should start from the app name.
Also, make sure Lunch is in the INSTALLED_APPS in the settings file.

Categories