django basic blog CSRF verification failed. Request aborted - python

I am trying to learn django. I am working on a basic blog, and right now I want to be able to add posts. I would like to do this with a post request and call a method that saves what is in the form into my db. Right now I am having trouble with csrf stuff. I know there are a lot of posts on this but I have looked through many of them and not been able to solve my problem. I have tried adding {% csrf_token %} , but that didn't work. I tried clearing my browser cache/cookies. I added the csrf to my middleware. So if anybody could help me figure this out I would appreciate it. And I have also seen a notation of {% url some something %} but I haven't been able to figure out what it does. I would really appreciate any help
models.py
from django.db import models
class Post(models.Model):
text = models.TextField(max_length=250)
time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.text
views.py
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response, redirect
from blog.models import Post
def home(request):
try:
p = Post.objects.all()
except Post.DoesNotExist:
raise Http404
return render_to_response('index.html',
{'post':p})
def post(request, uID):
try:
p = Post.objects.get(pk=uID)
except:
raise Http404
return render_to_response('post.html',
{'post':p})
def delete(request, uID):
try:
p = Post.objects.get(pk=uID).delete()
except:
raise Http404
return render_to_response('delete.html',
{'post':p})
def new(request):
return render_to_response('new.html')
def add(request):
if request.method == 'POST':
c = {}
c.update(csrf(request))
p = Post(text=request.text)
p.save()
return render_to_response("index.html", c)
else:
raise Http404
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'blog.views.home', name='home'),
url(r'^(?P<uID>\d+)/$', 'blog.views.post', name='Post Id'),
url(r'^(?P<uID>\d+)/delete/$', 'blog.views.delete', name='del'),
url(r'^new/$', 'blog.views.new'),
url(r'^created/$', 'blog.views.added'),
# url(r'^myApp/', include('myApp.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
new.html
<html>
<body>
<h2> Create a new Post </h2>
<form method="post" action="">
{% csrf_token %}
Body: <input type="textarea" name="text">
<input type="submit" value="Submit">
</form>
</body>
</html>
settings.py
# Django settings for myApp project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'db.sqlite', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# 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 = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
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: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
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: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
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 = 'mbc+)59rb8$o_k2epu8bi#!8nv!8j^)r#)b#po+t=!#3xx_at2'
# 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',
'django.middleware.csrf.CsrfViewMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'myApp.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'myApp.wsgi.application'
TEMPLATE_DIRS = (
# 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',
'blog',
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# 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.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# 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,
},
}
}

You need to add csrf verification to the view as well as the html so it should be
def new(request):
context = {}
context.update(csrf(request))
return render_to_response("new.html", context)

Related

Nothing getting stored in django non-rel for google app engine

I am unable to save anything in my django non-rel development project..
I have google app engine sdk installed with django non -rel.
I can access the django admin page but cannot login because neither superuser is getting saved anywhere.
I tried creating user in manage.py shell.
But after closing the shell window, the user object i saved earlier was not there.
Please help me how to save data to database in django-non-rel..
My settings.py file is -
# Django settings for bookncart project.
# Initialize App Engine and import the default settings (DB backend, etc.).
# If you want to use a different backend you have to remove all occurences
# of "djangoappengine" from this file.
from djangoappengine.settings_base import *
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
# Activate django-dbindexer for the default database
DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': DATABASES['default']}
AUTOLOAD_SITECONF = 'indexes'
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# 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 = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
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 = False
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
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: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
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 = 'l#ng7t0n-q4eb_*#3r04f1r09jf=&emqddc4a0!=yrvz(tbr23'
# 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 = (
# This loads the index definitions, so it has to come first
'autoload.middleware.AutoloadMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'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',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'bookncart.urls'
TEMPLATE_DIRS = (
# 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',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
'django.contrib.staticfiles',
'djangotoolbox',
'autoload',
'dbindexer',
# djangoappengine should come last, so it can override a few manage.py commands
'djangoappengine',
)
# 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.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# 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,
},
}
}
and urls.py file is -
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'^$', 'bookncart.views.home', name='home'),
# url(r'^bookncart/', include('bookncart.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)),
)
the base settings for djangoappengine are these -
try:
from dev_appserver_version import DEV_APPSERVER_VERSION
except ImportError:
DEV_APPSERVER_VERSION = 2
# Initialize App Engine SDK if necessary.
try:
from google.appengine.api import apiproxy_stub_map
except ImportError:
from djangoappengine.boot import setup_env
setup_env(DEV_APPSERVER_VERSION)
from djangoappengine.utils import on_production_server, have_appserver
DEBUG = not on_production_server
TEMPLATE_DEBUG = DEBUG
ROOT_URLCONF = 'urls'
DATABASES = {
'default': {
'ENGINE': 'djangoappengine.db',
# Other settings which you might want to override in your
# settings.py.
# Activates high-replication support for remote_api.
# 'HIGH_REPLICATION': True,
# Switch to the App Engine for Business domain.
# 'DOMAIN': 'googleplex.com',
# Store db.Keys as values of ForeignKey or other related
# fields. Warning: dump your data before, and reload it after
# changing! Defaults to False if not set.
# 'STORE_RELATIONS_AS_DB_KEYS': True,
'DEV_APPSERVER_OPTIONS': {
'use_sqlite': True,
# Optional parameters for development environment.
# Emulate the high-replication datastore locally.
# TODO: Likely to break loaddata (some records missing).
# 'high_replication' : True,
# Setting to True will trigger exceptions if a needed index is missing
# Setting to False will auto-generated index.yaml file
# 'require_indexes': True,
},
},
}
if on_production_server:
EMAIL_BACKEND = 'djangoappengine.mail.AsyncEmailBackend'
else:
EMAIL_BACKEND = 'djangoappengine.mail.EmailBackend'
# Specify a queue name for the async. email backend.
EMAIL_QUEUE_NAME = 'default'
PREPARE_UPLOAD_BACKEND = 'djangoappengine.storage.prepare_upload'
SERVE_FILE_BACKEND = 'djangoappengine.storage.serve_file'
DEFAULT_FILE_STORAGE = 'djangoappengine.storage.BlobstoreStorage'
FILE_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024
FILE_UPLOAD_HANDLERS = (
'djangoappengine.storage.BlobstoreFileUploadHandler',
'django.core.files.uploadhandler.MemoryFileUploadHandler',
)
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'TIMEOUT': 0,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
if not on_production_server:
INTERNAL_IPS = ('127.0.0.1',)
please help me how to get database settings working..
i am unable to find a solution from 2 days
You can change your
ALLOWED_HOSTS = ['<Name of Application in YAML>.appspot.com']
For more details on ALLOWED_HOSTS

Django flatpages with tiny-mce won't work

I can't get tiny-mce to work with django flatpages.
I am using Python 2.7 and django 1.5.2
I am following the instructions at http://django-tinymce.readthedocs.org/en/latest/installation.html
The following diagram shows my directory structure https://lh3.googleusercontent.com/-QtdsQE8WOak/UhZlsKIigRI/AAAAAAAADFw/9j4oLT6v1Nw/w764-h354-no/cms.png
The flatfiles are working but I get none of the rich text editor features.
I also don't get any error message.
Below I show how I have my files.
My settings.py file is as follows:
Django settings for cms project.
import os
PROJECT_DIR = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'cms.db', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# 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 = 'Greenwich'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-gb'
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: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
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: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
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 = 'tbbge^_ak_4h*#sm&0_%%ys)hgf3d*nc&%ac_r0zy)!wi(lo14'
# 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',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'cms.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'cms.wsgi.application'
TEMPLATE_DIRS = (
# 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.
os.path.join(PROJECT_DIR, '../templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.flatpages',
'tinymce',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
TINYMCE_JS_URL = 'http://localhost:8080/tiny_mce/tiny_mce_src.js'
TINYMCE_JS_ROOT = 'http://localhost:8080/tiny_mce'
TINYMCE_DEFAULT_CONFIG = {
'plugins' : "table,spellcheck,paste,searchreplace",
'theme' : "advanced",
'cleanup_on_startup': True,
'custom_undo_redo_levels' : 10,
}
TINYMCE_SPELLCHECKER = True
TINYMCE_COMPRESSOR = True
# 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.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# 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,
},
}
}
My urls.py file is as follows:
from django.conf.urls import patterns, include, url
from django.contrib.flatpages.models import FlatPage
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'cms.views.home', name='home'),
# url(r'^cms/', include('cms.foo.urls')),
# (r'', include('django.contrib.flatpages.urls')),
(r'tinymce/', include('tinymce.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)),
)
My models.py file is as follows:
from django import forms
from django.contrib.flatpages.models import FlatPage
from tinymce.widgets import TinyMCE
class FlatPageForm(forms.ModelForm):
content = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows':30 }))
class Meta:
model = FlatPage
My default.html is as follows:
<html>
<head>
<title>{{ flatpage.title }}</title>
</head>
<body>
<h1>{{ flatpage.title }}</h1>
{{ flatpage.content }}
</body>
</html>
I think you need to register the new form with django admin. Try replacing your models.py with this:
from django.contrib import admin
from django import forms
from django.contrib.flatpages.admin import FlatPageAdmin, FlatpageForm
from django.contrib.flatpages.models import FlatPage
from tinymce.widgets import TinyMCE
class MyFlatpageForm(FlatpageForm):
content = forms.CharField(widget=TinyMCE(attrs={'cols': 80,
'rows':30 }))
class MyFlatPageAdmin(FlatPageAdmin):
form = MyFlatpageForm
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, MyFlatPageAdmin)
There are a couple of other things that might need to be fixed. The models.py won't be discovered if you don't have "cms" in your installed apps. Also, I think the extension you want is "spellchecker" not "spellcheck".

Haystack-Django TemplateDoesNotExist at /search/ Error

I am trying to integrate haystack into my Django App
Here is the DIR structure :
vaibhav#ubuntu:~/temp/hayStackDemo/demoApp/templates/search$
pwd
/home/vaibhav/temp/hayStackDemo/demoApp/templates/search
vaibhav#ubuntu:~/temp/hayStackDemo/demoApp/templates/search$ ls
indexes search.html
And i am getting this error : TemplateDoesNotExist at /search/
And some Django DEBUG Info :
Template-loader postmortem
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
/usr/local/lib/python2.7/dist-packages/django/contrib/auth/templates/search/search.html (File does not exist)
/usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/search/search.html (File does not exist)
/usr/local/lib/python2.7/dist-packages/haystack/templates/search/search.html (File does not exist)
/home/vaibhav/temp/hayStackDemo/demoApp/templates/search/search.html (File does not exist)
I did not understand why i am getting this error... where i have done wrong...
settings.py :
# Django settings for hayStackDemo project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '/home/vaibhav/temp/hayStackDemo/sqlite.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# 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 = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
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.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
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.
# Example: "http://media.lawrence.com/static/"
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 = '=7*wk#+p^*)zghrt)+021wh%uj&si+f^8yw%j6+2yo%1)w^vy7'
# 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 = 'hayStackDemo.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'hayStackDemo.wsgi.application'
TEMPLATE_DIRS = (
'/home/vaibhav/temp/hayStackDemo/demoApp/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',
'haystack',
'demoApp'
)
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://127.0.0.1:9200/',
'INDEX_NAME': 'haystack',
},
}
# 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.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# 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.contrib import admin
from django.conf.urls import patterns, include, url
#------------------------------------------------------------------------------
admin.autodiscover()
urlpatterns = patterns('',
# url(r'^$', 'HayStackDemo.views.home', name='home'),
# url(r'^HayStackDemo/', include('HayStackDemo.foo.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^search/', include('haystack.urls'))
)
It's possible the problem is on file "search.html". Change this:
{% extends 'base.html' %}
by this:
{% extends 'myapp/base.html' %}
See the solution on bottom of this page: https://github.com/django-haystack/django-haystack/issues/1205
Sometimes this error is cause by failure to include your app in INSTALLED_APPS in settings.py. Check to make sure your app is installed

Ldap authentication using django_auth_ldap

I am trying to achieve Ldap authentication using django.
For that I have configured my settings.py as mentioned here http://pythonhosted.org/django-auth-ldap/example.html
I am attaching my settings.py file here
import ldap
import os
from django_auth_ldap.config import LDAPSearch
# Django settings for mysite project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
AUTH_LDAP_CONNECTION_OPTIONS = {
ldap.OPT_REFERRALS: 0
}
AUTH_LDAP_BIND_DN = "cn=admin,dc=server,dc=com"
AUTH_LDAP_BIND_PASSWORD = ""
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=People,dc=server,dc=com",ldap.SCOPE_SUBTREE, "(uid=%(user)s")
AUTH_LDAP_SERVER_URI = "ldap://ldap.server.com"
AUTH_LDAP_ALWAYS_UPDATE_USER = False
MANAGERS = ADMINS
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'nameofdatabase', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': 'someuser',
'PASSWORD': 'somepassword',
'HOST': '/tmp/mysql.sock', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# 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/Kolkata'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
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
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
# 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: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(SITE_ROOT, 'static')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
#MEDIA_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/media/'
LOGIN_URL = '/login/'
# 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: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
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 = 'some_secret_key'
# 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 = 'mysite.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'mysite.wsgi.application'
TEMPLATE_DIRS = (
# 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.
os.path.join(SITE_ROOT, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
'polls',
#'ldapauthentication'
'portal',
)
# 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.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# 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,
},
}
}
Is there anything else apart to do from this ?
My views.py file is as follows
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_protect
from django_auth_ldap.backend import LDAPBackend
# Create your views here.
#login_required
#csrf_protect
def portal_main_page(request):
"""
If users are authenticated, direct them to the main page. Otherwise, take
them to the login page.
"""
if request.user.is_authenticated():
user = request.user.is_authenticated()
return render_to_response('portal/index.html')
My models.py file is empty. I am simply not able to authenticate the users?
What else do I need to do. From what I found out it is just trying to authenticate against the local database. I could not get any further help from http://pythonhosted.org/django-auth-ldap/#auth-ldap-bind-as-authenticating-user
I have checked similar questions here but could not make out anything from the answers from the users.
Kindly Help me, so that I can achieve the authentication.

Lose access to my app on dashboard in Django

When I set settings.DEBUG=False, I lose access to my apps in the dashboard except auth and sites. It work fine with settings.DEBUG=True.
# Django settings for blog project.
import sys
PROJECT_PATH=r'/home/www/blog'
if not PROJECT_PATH in sys.path:
sys.path.insert(0,PROJECT_PATH)
DEBUG =False
TEMPLATE_DEBUG =False
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '/home/www/blog/database.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # 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:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Asia/Shanghai'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'zh-cn'
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 = '/home/www/blog/media/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# 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 = '/home/www/blog/staticDir/'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
'/home/www/blog/static/',
# 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',
)
# 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 = 'blog.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'blog.wsgi.application'
TEMPLATE_DIRS = (
'/home/www/blog/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',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'article',
'guestbook',
'multimedia',
'archive',
'about',
)
# 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.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# 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,
},
}
}
here is an app named article:
# coding:utf-8
from markdown import markdown
import datetime
from django.db import models
from django.contrib import admin
VIEWABLE_STATUS = [2,]
class ViewableManager(models.Manager):
"""
改写 Model.objects 的 get_query_set 方法
objects 不能接触状态为不可见的 Article 类的实体
"""
def get_query_set(self):
default_queryset = super(ViewableManager, self).get_query_set()
return default_queryset.filter(status__in=VIEWABLE_STATUS)
class Article(models.Model):
"""
文章类
"""
STATUS_CHOICES=((1,'Editing'),
(2,'Posted'),)
articleID=models.AutoField(primary_key=True)
title=models.CharField(max_length=50,unique=True)
slug = models.SlugField(max_length=50,unique=True)
postDate=models.DateField()
lastUpdate=models.DateTimeField(auto_now=True,auto_now_add=True)
keywords=models.CharField(max_length=140,blank=True)
markdown_content=models.TextField()
html_content=models.TextField(editable=False)
status=models.IntegerField(choices=STATUS_CHOICES,default=1)
class Meta:
ordering=['-postDate','-lastUpdate']
def get_url(self):
return r'/article/'+str(self.slug)
def __unicode__(self):
return self.title
def saveCategories(self):
self.articleCategories.clear()
categoryList=self.keywords.split()
for category in categoryList:
c=Category.objects.filter(label=category)
if c:
self.articleCategories.add(c[0])
else:
self.articleCategories.create(label=category)
def save(self):
self.html_content=markdown(self.markdown_content)
self.lastUpdate=datetime.datetime.now()
super(Article,self).save()
self.saveCategories()
print self.html_content
print self.lastUpdate
super(Article,self).save()
admin_objects=models.Manager()
objects=ViewableManager()
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title', 'status', 'postDate', 'lastUpdate')
search_fields = ('title', 'keywords','content')
list_filter = ('status', 'postDate', 'lastUpdate')
admin.site.register(Article, ArticleAdmin)
class Category(models.Model):
label=models.CharField(max_length=30,unique=True)
masterArticle=models.ManyToManyField(Article,related_name='articleCategories',blank=True)
class Meta:
verbose_name_plural = "categories"
def __unicode__(self):
return self.label
class CategoryAdmin(admin.ModelAdmin):
pass
admin.site.register(Category, CategoryAdmin)
And other app named guestbook
# coding:utf-8
from django.db import models
from django.contrib import admin
from md5 import md5
from article.models import Article
class guestMessage(models.Model):
guestName=models.CharField(max_length=50)
guestEmail=models.EmailField(max_length=75)
gravatarHash=models.CharField(max_length=33,blank=True)
content=models.TextField()
postDate=models.DateTimeField(auto_now_add=True)
article=models.ForeignKey(Article,blank=True,null=True,
related_name='guestMessage')
def save(self):
super(guestMessage,self).save()
self.gravatarHash=(md5(self.guestEmail)).hexdigest()
super(guestMessage,self).save()
class guestMessageAdmin(admin.ModelAdmin):
list_display = ('guestName', 'article', 'postDate')
search_fields = ('guestName', 'article','content')
list_filter = ('article', 'postDate')
admin.site.register(guestMessage, guestMessageAdmin)
here is the urls.py
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += patterns('article.views',
url(r'^$', 'index'),
url(r'^article/([\S]+)$', 'articleDetail'),
url(r'^category/([\S]+)$','articleBYcategory'),
url(r'^search/$','atricleSearch'),
)
urlpatterns += patterns('guestbook.views',
url(r'^guestbook/$','guestbook'),
)
urlpatterns += patterns('archive.views',
url(r'^archive/$','archive'),
)
urlpatterns += patterns('about.views',
url(r'^about/$','about'),
)
www.mysite.com/admin: there is no add or change link . I don't have permission?
pic link: http://img3.douban.com/view/photo/photo/public/p1499852307.jpg
I have no other ideas than move registering admin sites out of models. Official docs say about them residing in separate admin module.

Categories

Resources