I am using Django in conjunction with MongoDB using mongoengine. I was following the tutorial on https://docs.djangoproject.com/en/1.7/intro/tutorial02/ and therefore wanted to create a superuser and log in. Creation worked without problem appearantly. However when I tried to log in, I was greeted by the following site:
I suppose this has to do with my initialization of the database using the dummy database in the settings.py. However I was told using mongoengine requires to do it this way and it did not cause problems earlier. Anyway: here is the content of my settings.py
"""
Django settings for myproject 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 = 'xg0wnp^w)i#svh13#^v45**4^3v-at#ktre=^n#cw2!6(q__gq'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.auth',
'mongoengine.django.mongo_auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
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'
import mongoengine
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
#DATABASES = {
# 'default' : {
# 'ENGINE' : 'django_mongodb_engine',
# 'NAME' : 'my_database'
# }
#}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
#}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.dummy',
}
}
mongoengine.connect(db='local', alias ='default')
#from django.contrib.auth import get_user_model
#user = get_user_model().objects.create_user(**user_data)
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
AUTH_USER_MODEL = 'mongo_auth.MongoUser'
MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User'
#MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User'
#SESSION_ENGINE = 'mongoengine.django.sessions'
#SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer'
#_MONGODB_USER = 'mongouser'
#_MONGODB_PASSWD = 'password'
#_MONGODB_HOST = 'thehost'
#_MONGODB_NAME = 'thedb'
#_MONGODB_DATABASE_HOST = \
# 'mongodb://%s:%s#%s/%s' \
# % (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME)
#mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)
#AUTHENTICATION_BACKENDS = (
# 'mongoengine.django.auth.MongoEngineBackend',
#)
# 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/'
Kindly configure the following settings in setting.py file
import mongoengine
DATABASES = {
'default': {
'ENGINE': '',
},
}
SESSION_ENGINE = 'mongoengine.django.sessions' # optional
_MONGODB_USER = 'mongouser'
_MONGODB_PASSWD = 'password'
_MONGODB_HOST = 'thehost'
_MONGODB_NAME = 'thedb'
_MONGODB_DATABASE_HOST = \
'mongodb://%s:%s#%s/%s' \
% (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME)
mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
I hope the above solution will resolve your issue.
what to do if database-engine not needed
default database is used by some of the default authentication APIs
used in Middleware-Apps.
try to make your MIDDLEWARE_APPS tuple as follows:
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',
)
I am just a beginner, so if any more errors come around please do comment.
This solution breaks the default Admin Panel backend provided by Django. I'm trying to find a work around for the same.
Redirecting to a different view in urls.py for admin page may help
though
Related
I'm working on a very basic Django app in hopes of teaching myself the framework, and I've hit a small snag. The app is intended to take user input, store it in a mysqlite database, and display the contents of the database on receiving a request. I have everything working properly when the app is run locally (manage.py runserver), however it's misbehaving once it's deployed. For some reason, the storage logic is malfunctioning on the live site (Windows Server 2012 via MS Azure).
Here is the code in question:
from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import render_to_response
from helloworld.models import Registry
def home(request):
return render_to_response("home.html")
def register(request):
return render_to_response("register.html")
def view(request):
entries = Registry.objects.all()
args = {}
args["entries"] = entries
return render_to_response("registry.html", args)
def submit(request):
nameIn = request.GET.get('name')
ageIn = request.GET.get('age')
monthIn = request.GET.get('month')
try:
Registry(name=nameIn, age=ageIn, month=monthIn).save()
except:
pass
return view(request)
I've done a fair amount of debugging, and tried several approaches to storing the data. I've checked that the method is receiving valid values. I can't, for the life of me, figure out why that call to save() is throwing an error. Hopefully it will be obvious to one of you Django-pros! THanks in advance, any help will be greatly appreciated! P.s. I'm attaching my settings file, as i have a sneaking suspicion that poor configuration is the source of my troubles.
"""
Django settings for cny_solar 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 = 's7xv#m=5h=mjrdg_7-$=7kr8kx4np9$#6qzlg+m4xt&6-#-zi2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS=['127.0.0.1','localhost']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'helloworld',
)
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 = 'helloworld.urls'
WSGI_APPLICATION = 'helloworld.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
# 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_ROOT = BASE_DIR
STATIC_URL = '/static/'
STATICFILES_DIRS = (
('assets', os.path.join(BASE_DIR, 'static')),
)
I've been trying to deploy the static .css files and stuff for a website my classmates and I have been doing. Right now we have kind of crap styling and stuff so we decided to use some code from Bootstrap to make it looks nice.
After editing my settings.py and doing python manage.py collectstatic, the static files were put into the static/ folder. Upon using the runserver command, none of the styling changes have been made. I've been looking on Google for a while but I have not discovered the solution.
I want to get it working on my local machine before I push it to PythonAnywhere.
Any help will be appreciated.
Here is my settings.py file
"""
Django settings for Dreadnaught 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 = GOTCHA!
# 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',
'TTT'
)
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 = 'Dreadnaught.urls'
WSGI_APPLICATION = 'Dreadnaught.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'Dreadnaught',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '',
'PORT': '',
}
}
# 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/'
STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = ()
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATE_DIRS = (TEMPLATE_PATH,)
If you want to serve your css and js files in production mode you must change Debug true to false.
DEBUG=False
For reference STATIC
I have deployed my django project in pythonanywhere without any databases required, I am getting the error- DATABASES is improperly configured . The link to my deployed project is -http://drchitradhawle.pythonanywhere.com/
My setting.py file is-
# 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 = 'fi+9_egiio(7l6xvbgk%o=!k(ktn3!ywhc4+p_6^57j4yvl0tp'
# 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',
'webpage',
)
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 = 'website.urls'
WSGI_APPLICATION = 'website.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {}
# 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_ROOT = "/home/DrChitraDhawle/website/webpage/static"
STATIC_URL = '/static/'
STATICFILES_DIR = (
('assets', '/home/DrChitraDhawle/website/webpage'),
)
#
#STATICFILES_DIR = [os.path.join(BASE_DIR, '')]
MEDIA_URL = 'http://localhost:8085/media/'
Django needs a database to store information such as session/cookie info. So even if you don't use the database for your own website stuff, you still need one.
Fortunately, just using the default sqlite settings, and then running ./manage.py syncdb should be enough to get everything working for now.
Although you don't want to use database in your project but still you have to give database defination as #conrad said. So you can use sqlite3, a file based database that does not require setting up a database account and password.
Set up your database setting as -
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/home/<username>/<ProjectName>/db.sqlite',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': ''
}
}
After that run the below command in console -
python ./manage.py syncdb
Now you will be asked for password, username and email-Id for creating superuser for database.
And its all done!
I'm trying to get the login_required decoration in django working.
My view looks like this
#login_required
def index(request):
if request.user.is_authenticated():
print 'in'
else:
print 'out'
context = {'test_obj': 'Testing Testing 123'}
return render(request, 'web_copo/index.html', context)
and my settings.py like this
# 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',
'web_co',
)
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 = 'project_copo.urls'
WSGI_APPLICATION = 'project_copo.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'co_db',
'USER': 'root',
'PASSWORD': 'xxx',
'Host': '127.0.0.1',
'Port': '',
}
}
# 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/
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
STATIC_URL = '/static/'
TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
'django.core.context_processors.csrf',
every time I navigate to the page, it lets me straight in. Also it prints 'in', meaning that django thinks my user is already logged in. Since I haven't logged in, I don't why this is happening. What am I doing wrong?
Thanks.
If you're logged in as root, try going to your admin and log out.
Also, you can try your browser's incognito window/tab. That way you will have new session in each window/tab.
I am able to browse django admin login page but upon keying in correct login details it will stay on the same login page with empty textboxes. It will show messages if login details are wrong though.
I have the following, what ways can I troubleshoot as the log doesn say anything significant.
What the ways to test login on the shell?
Use manage.py createsuperuser to create superuser as I missed the default one during running syncdb
Cleared cookies and retry still the same.
Correct SITE_ID in settings.py
settings.py
import logging
import pwd
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DEBUG_TOOLBAR = False
PROFILER_ON = False
INTERNAL_IPS = (
'127.0.0.1'
)
ADMINS = (
('Admin', 'test#domain.com'),
)
SEND_BROKEN_LINK_EMAILS = False
MANAGERS = ADMINS
DEFAULT_FROM_EMAIL = 'test#domain'
SERVER_EMAIL = DEFAULT_FROM_EMAIL
EMAIL_HOST = 'test'
UPLOAD_ROOT = '/domain/uploads'
PUBLIC_UPLOAD_ROOT = '/domain/htdocs/public_uploads'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'table_name',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
# use this to create InnoDB tables
'OPTIONS': {
'init_command': 'SET storage_engine=InnoDB',
'charset': 'utf8',
}
}
}
#SESSION_COOKIE_SECURE = True
# Setup logging
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
}
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
LANGUAGES = (
('en-us', _('English(US)')),
)
SITE_ID = 1
SITE_NAME = 'my site'
USE_I18N = True
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
MEDIA_URL = '/media/'
PUBLIC_UPLOAD_URL = '/public_uploads/'
UPLOAD_URL = '/uploads/'
UPLOAD_IMAGES_DIR = 'images/'
ADMIN_MEDIA_PREFIX = '/djangomedia/'
SECRET_KEY = 'test'
#SESSION_COOKIE_HTTPONLY = True
#SESSION_COOKIE_DOMAIN = 'domain'
# 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',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/users/main/'
# The URL where requests are redirected for logout.
LOGOUT_URL = '/logout/'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages',
)
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
ROOT_URLCONF = 'myapp.urls'
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.flatpages',
)
urls.py
url(r'^admin/', include(admin.site.urls)),
It was actually due to SESSION_COOKIE_SECURE = True in my settings.py, I had it accidentally defined in 2 places, one commented another one uncommented causing that to happen since the site is not running under https yet. It was silly mistake – user1076881 Apr 5 at 7:27