django + uwsgi + ngnix = Django CSRF verification error - django

I have a simple application that allows you to upload images onto the server and it is set up on my production server which consist of of django + uwsgi + ngnix . Now the problem is the csrf token doesn't appear in the template and when I try to upload an image it display this error
Forbidden (403)
CSRF verification failed. Request aborted.
Reason given for failure:
CSRF token missing or incorrect.
I understand this error clearly . {% csrf_token %} is inside the template and the csrf is enabled on MIDDLEWARE_CLASSES . I also tested my application on development server and it works fine . What can cause the {% csrf_token %} to not appear in the template on my production server.
I can see the form but when I view the source there is no csrf token.
settings
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/projects/mysite/d.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.
}
}
ALLOWED_HOSTS = []
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
U SE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = '/home/projects/mysite/media/'
MEDIA_URL = '/media/'
STATIC_ROOT = ''
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',
)
ist 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.
)
views
def upload(request):
form = ImageForm()
if request.POST:
form = ImageForm(request.POST, request.FILES)
image = request.FILES.get('image')
CarPhoto.objects.create(user=request.user,cars=1,description='dwq',image=image)
return render(request,'image.html',{'form':form})
template
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div id="c">image</div> {{form.image}}
dwqdwqdwq
<input type = "submit" value= "add" id="box2"/>
</form>{% csrf_token %}
view source
<form method="POST" enctype="multipart/form-data"><div id="c">image</div><input id="id_image" name="image" type="file" /> dwqdwqdwq <input type="submit" value="add" id="box2"/></form>

Your view is missing the token since you're not setting it.
Change this line
return render(request,'image.html',{'form':form})
to
context = {'form':form,}
context.update(csrf(request))
return render(request,'image.html', context)
or
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
return render_to_response('image.html', context, context_instance=RequestContext(request))
You can use either depending on your flavor, also, you have to {% csrf_token %}s in your template. The one outside of the <form> is redundant.
Reading the docs is good!

Related

Django Files Upload from Form get CSRF Forbidden on production

I have a simple Django FileForm for multiple files upload (basically txts with polygon coordinates). I don't want to save the uploaded files anywhere but only treat them on the fly (memory?) and return a leaflet map with the polygons and a new file of mine (which transforms and exports all the txts in a .dxf format file (CAD combatible)).
I have done all the logic and my programm seems to work fine on development but on production (Heroku) when i hit the submit button on my form I keep getting CSRF Forbidden 403 message. I am really frustrated. I have used csfr decorators (csrf_exempt, requires_csrf_token, ensure_csrf_cookie) on my views but none seems to work. I have included
enctype="multipart/form-data"> and {% csrf_token %} on my form template.
What's the problem? It's hard for me to test and try because on development everything is ok and I have to deploy everytime only to see if another approach works.
Is it because I am not saving the files on a model and on a disk (What's the logic here?), or is it because I'm missing something on the CSRF part on my settings?
settings.py (when deploying)
"""
Django settings for myKAEK project.
Generated by 'django-admin startproject' using Django 4.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
import os
from decouple import config
from decouple import config, Csv
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'mykaek-gr.herokuapp.com', 'myKAEK.gr', 'www.myKAEK.gr']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'djgeojson',
'storages',
'debug_toolbar',
'myKAEKapp',
]
MIDDLEWARE = [
"debug_toolbar.middleware.DebugToolbarMiddleware",
'django.middleware.security.SecurityMiddleware',
'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',
]
INTERNAL_IPS = [
"127.0.0.1",
]
ROOT_URLCONF = 'myKAEK.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'myKAEK.wsgi.application'
GOOGLE_MAPS_API = config('GOOGLE_MAPS_API')
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.contrib.gis.db.backends.postgis',
# 'NAME': config('DB_NAME'),
# 'USER': config('DB_USER'),
# 'PASSWORD': config('DB_PASSWORD'),
# 'HOST': config('DB_HOST'),
# 'PORT': config('DB_PORT'),
# }
#}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
# STATIC_URL = 'static/'
# STATIC_ROOT = os.path.join(BASE_DIR)
# STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
# MEDIA_URL = '/media/'
# MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
USE_S3 = config('USE_S3') == 'TRUE'
if USE_S3:
# aws settings
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_DEFAULT_ACL = 'public-read'
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
# s3 static settings
AWS_LOCATION = 'static'
STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
# s3 public media settings
PUBLIC_MEDIA_LOCATION = 'media'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
# 'myKAEKapp.storage_backends.PublicMediaStorage'
else:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
# MEDIA_URL = '/mediafiles/'
# MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Heroku: Update database configuration from $DATABASE_URL.
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=120)
DATABASES = { 'default': dj_database_url.config() }
DATABASES['default'].update(db_from_env)
DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.postgis'
CSRF_TRUSTED_ORIGINS = ["https://mykaek-gr.herokuapp.com/", "https://mykaek.gr/"]
forms.py
class UploadFileForm(forms.Form):
files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
html
<div class="row justify-content-center align-items-center text-center" style="padding-top: 30px; width: 500px; margin: auto;">
<fieldset name="Multiple Files Upload">
<form method="post" action="/draw-polygons/" enctype="multipart/form-data">{% csrf_token %}
<dl><input class="form-control" type="file" id="formFileMultiple" name="files" required multiple></dl>
<button type="submit" class="btn btn-outline-dark" style="margin-top: 10px;">Φόρτωση</button>
</form>
</fieldset>
</div>
view.py
def upload_multiple_files(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
files_list = request.FILES.getlist('files')
if form.is_valid():
for f in files_list:
try:
'''my code here'''
except:
'''my code here'''
'''my code here'''
return render(request, "multiple/success.html", context)
else:
form = UploadFileForm()
return render(request, 'multiple/multiple.html', {'title': 'myKAEK.gr | Draw Polygons', 'form': form})
def txt_dxf(request):
topos = cache.get('topos')
doc = ezdxf.new("R2000")
msp = doc.modelspace()
doc.layers.add('POLYS_FROM_TXTS')
for i in topos:
msp.add_lwpolyline(i, dxfattribs={"layer": "POLYS_FROM_TXTS"})
out = io.BytesIO()
doc.write(out, fmt='bin')
out.seek(0)
return FileResponse(out, as_attachment=True, filename='polygons_from_txt.dxf')
urls
urlpatterns = [
path('draw-polygons/', views.upload_multiple_files, name='upload_multiple_files'),
path('draw-polygons/export_dxf/', views.txt_dxf, name='txt_dxf'),
]
If I may add something I saw after my original question was posted:
While my custom domain served through cloudflare returns
CSRF Forbidden 403, my herokuapp server returns for the same page
Bad request 400
I don't know if it's relevant but I thought I should add.
Also when I use #csrf_exempt on my view and delete {% csrf_token %} from template I get 400 Bad Request on my custom domain too.
Is it beacouse I use Cloudflare (with cache disabled) between my custom domain and herokuapp?
Please help I really need to get this function work.
Try doing this using Django Forms, it will save you from writing extra code and will handle such edge cases.
https://docs.djangoproject.com/en/4.1/topics/http/file-uploads/#uploading-multiple-files

Django Oscar: Nothing showing up at URL "http://localhost:8000/buy/"

I wanted to include an ecommerce portal on my website and I have done everything as given on the "Create your Shop page" as given in Django-Oscar documentation, just that in
urls.py instead of
url(r'', include(application.urls)),
I have added
url(r'^buy/', include(application.urls)),
but the problem is that when I hit the url it is neither showing anything nor giving an error.
Any idea what could be the problem?
It could be some urls are clashing or something else trivial but I am not able to understand from where to start debugging.
File urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from view import AboutusView, TwentySevenView
import apps.users.views
from django.conf import settings
#oscar urls
from oscar.app import application
admin.site.site_header = ''
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'torquehp.views.home', name='home'),
# url(r'^users/', include('users.urls')),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^admin/', include(admin.site.urls)),
url(r'^about-us/$', AboutusView.as_view(), name="about-us"),
url(r'^24x7/$', TwentySevenView.as_view(), name="24x7"),
url(r'^$', apps.users.views.user_home, name="home"),
url(r'^markdown/', include('django_markdown.urls')),
url(r'^users/', include('apps.users.urls')),
url(r'^doorstep/', include('apps.doorstep.urls')),
url(r'^cars/', include('apps.cars.urls')),
url('', include('social.apps.django_app.urls', namespace='social')),
# urls for zinnia
url(r'^blog/', include('zinnia.urls', namespace='zinnia')),
url(r'^comments/', include('django_comments.urls')),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, }),
# oscar URLs
url(r'^buy/', include(application.urls)),
)
File settings.py
import os
import sys
from oscar import get_core_apps
from oscar import OSCAR_MAIN_TEMPLATE_DIR
from oscar.defaults import *
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
location = lambda x: os.path.join(
os.path.dirname(os.path.realpath(__file__)), x)
# sys.path.insert(0, os.path.join(BASE_DIR, 'apps')) # to store apps in apps/ directory
# 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 = ''
# 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',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.flatpages',
'apps.users',
'apps.doorstep',
'apps.cars',
'django_markdown',
'social.apps.django_app.default',
'django.contrib.sites',
'django_comments',
'mptt',
'tagging',
'zinnia',
'compressor',
] + get_core_apps()
# specifying the comments app
# COMMENTS_APP = 'zinnia_threaded_comments'
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',
'oscar.apps.basket.middleware.BasketMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
# Authentication backend used by python-social-auth
AUTHENTICATION_BACKENDS = (
'social.backends.facebook.FacebookOAuth2',
'social.backends.google.GoogleOAuth2',
'django.contrib.auth.backends.ModelBackend',
'oscar.apps.customer.auth_backends.EmailBackend',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"social.apps.django_app.context_processors.backends",
"social.apps.django_app.context_processors.login_redirect",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.i18n",
"django.core.context_processors.request",
"zinnia.context_processors.version",
"django.core.context_processors.debug",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
'oscar.apps.search.context_processors.search_form',
'oscar.apps.promotions.context_processors.promotions',
'oscar.apps.checkout.context_processors.checkout',
'oscar.apps.customer.notifications.context_processors.notifications',
'oscar.core.context_processors.metadata'
)
# TEMPLATE_LOADERS = (
# 'app_namespace.Loader',
# )
ROOT_URLCONF = 'torquehp.urls'
WSGI_APPLICATION = 'torquehp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "",
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306'
}
}
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOGIN_URL = '/users/login/'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = "/media/"
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates').replace('\\', '/'),
location('templates'),
OSCAR_MAIN_TEMPLATE_DIR,
)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'staticfiles'),
)
REGISTRATION_INVALID = 50
MESSAGE_TAGS = {
REGISTRATION_INVALID: 'InvalidDetails',
}
# temporary , should not be in settings file
SOCIAL_AUTH_FACEBOOK_KEY = ""
SOCIAL_AUTH_FACEBOOK_SECRET = ""
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = ""
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = ""
LOGIN_REDIRECT_URL = '/blog/'
# ------------------------------------ #
# Settings for sending email #
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
SERVER_EMAIL = EMAIL_HOST_USER
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# ------------------------------------ #
# site id for django sites framework
SITE_ID = 1
# configuration settings for django-zinnia
ZINNIA_PING_EXTERNAL_URLS = False
ZINNIA_SAVE_PING_DIRECTORIES = False
ZINNIA_MARKUP_LANGUAGE = 'markdown'
ZINNIA_UPLOAD_TO = 'uploads/zinnia/'
# TimeZone Settings
USE_TZ = True
# ------------------------ #
# django s=oscar search settings
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
},
}
Screenshots:
http://localhost:8000/buy/
http://localhost:8000/buy/catalogue/
I see that in your second screenshot localhost:8000/buy/catalogue/ you actually get a result. It would seem as if you haven't defined your own templates or somehow need to fix your TEMPLATE_DIRS or TEMPLATE_CONTEXT_PROCESSORS settings.
I haven't used oscar, but that fact that you get something on screen seems like a template loading issue to me.
See their docs about setting the template_context_processors
Can you post your settings please?
Update:
After seeing your settings, the template_context_processors look correct. I next looked at oscar's templates and they seem to extend without qualifying the oscar directory. For example, layout.html (/oscar/templates/oscar/layout.html) does this:
{% extends 'base.html' %}
Now, if you also have a 'base.html' file in your own project directory, say project_dir/templates/base.html, then it'll probably use that instead. Can you try to temporarily rename that file (if it exists) and see what happens?
urls.py
url(r'^buy/', include("app.urls")),
Then under your app directory create a file called urls.py
app/urls.py
# this is your “http://localhost:8000/buy/”
url(r'^$', ViewName.as_view(), name="thename"),
In app/urls.py add the following line:
url(r'^$',views.index,name='index'),
This will redirect you to the index function in app/views.py
In app/views.py do something like that:
def index(request):
#Your logic here
return render(request,'urpoll/index.html'{'category':categorys,'ques':ques,'url':url})
This will render index.html with categories,ques,url. In index.HTML so something like that:
{{ if category }}
{{ category }}
{{ endif }}
I hope this will help.
Maybe you have a naming collision with templates. Django's default template loader, which I assume you're using, can be a bit unintuitive. When you ask it for a template with a given name, it goes through your INSTALLED_APPS tuple in settings in order, checking in each one for a templates folder. If there are two templates with the same path in two different apps, it will always take the first one it finds.
That's why the recommendation in django docs is to 'namespace' your templates by keeping them all in another folder with the name of your app, within the templates folder. Oscar does this, so their templates are in oscar/templates/oscar, so they shouldn't be colliding with any other apps, but I'm wondering if maybe you put an 'oscar' folder within the templates of one of your apps, possibly clashing with base.html.
The problem is that django-oscar is not meant to be included under a sub-path, such as /buy/. In their documentation, their example shows installing it as:
url(r'', include(application.urls)),
If you look at the source of get_urls(), which provides the return value for application.urls, you can see that it does not provide a urlpattern to match r'^$', which is what you would need to match at the URL you are trying to view.
In short, you should follow exactly what the documentation recommends, or you will get unexpected results.

How to achieve LDAP authentication in Django, How to access User object in View?

I want to build a site using Django wherein to enter it, the users have to authenticate themselves through LDAP server.
I have read the python-ldap configuration and configured settings.py accordingly. I'm able to authenticate a user from local database, but when I try to do it through LDAP, it doesn't work.
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = [os.path.join(BASE_DIR,'templates')]
import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
# Baseline configuration.
AUTH_LDAP_SERVER_URI = "ldap://10.1.10.10"
AUTH_LDAP_CONNECTION_OPTIONS = {
ldap.OPT_REFERRALS: 0
}
AUTH_LDAP_BIND_DN = "cn=myname,dc=example,dc=com"
AUTH_LDAP_BIND_PASSWORD = "dontevenask"
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com",
ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
#AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=example,dc=com"
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail"
}
AUTH_LDAP_ALWAYS_UPDATE_USER = True
AUTH_LDAP_FIND_GROUP_PERMS = True
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
# 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 = '^eh5xdkui7vw!^x&l%q44ak6+yglnx5q(tqwd8l+w!sxml7q!&'
# 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',
'my_app',
)
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 = 'users.urls'
WSGI_APPLICATION = 'users.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS':{
'read_default_file':'/home/user/config.cnf',
},
}
}
# 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/'
Here is my views.py file
def loggedin(request):
uid = request.user.username
return render_to_response('loggedin.html',
{'full_name':uid})
And the loggedin.html file
{% block content %}
<h2> Hi {{full_name}} Logged in! </h2>
<p> Click here to logout </p>
{% endblock %}
I did refer to other posts but didn't find the solution.
What am I missing?
There are several issues that might cause the LDAP authentication not to work.
I am assuming you are running linux host. Have you verified that the LDAP settings you have entered works properly? Use command line tool 'ldapsearch' verify that the server works and responses as you might expect.
After you have successfully authenticated with ldapsearch and the authentication is still not working in Django i suggest you put logging on on and paste the logs somewhere.
Without futher info its hard to say what part of your setup is incorrect.
So, here goes the answer!
I changed "(uid=%(user)s)") to "(samaccountname=%(user)s)") which did the trick.
Having the logger helped locate what the problem was - was it even talking to LDAP or just trying to authenticate with the local database.

Display images as Thumbnail

I want to display my uploaded images as a thumbnail in my template . I have installed the sorl-thumbnail in my installed app . when i am executing my application i am getting a template error like this :
Syntax error. Expected: thumbnail source geometry [key1=val1 key2=val2...] as var
Exception Location: /usr/local/lib/python2.7/dist-packages/sorl_thumbnail-11.12 py2.7.egg/sorl/thumbnail/templatetags/thumbnail.py in init, line 65
please help me to find the solution . my codes are as follows
class Photo(models.Model):
image = models.ImageField(upload_to='/home/forent/sites1/dreamaddress/media/uploads/properties/image')
tag=models.CharField(max_length=255, null=True,blank=True)
caption=models.CharField(max_length=755, null=True,blank=True)
prop=models.ForeignKey(Property,blank=True,null=True)
View :
def img_all(request):
imgs = Photo.objects.all()
return render_to_response('details.html',{'imgs':imgs},context_instance=RequestContext(request))
settings.py
# Django settings for dreamaddress project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
AUTH_PROFILE_MODULE = 'properties.UserProfile'
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'dreamaddress', # 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 = '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
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT ='/home/forent/sites1/dreamaddress/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/forent/sites1/dreamaddress/sitestatic/'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/sitestatic/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# 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.
'/home/forent/sites1/dreamaddress/properties/static/',
)
# 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 = 'gl=#6g+m6yw_j8-ybqme0-3w+iz81ib185twqh9-l%m32a6=_j'
# 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',
)
ROOT_URLCONF = 'dreamaddress.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.
'/home/forent/sites1/dreamaddress/template/'
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'properties',
'south',
'sorl.thumbnail',
# Uncomment the next line to enable the admin:
# '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.
# 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,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
details.html :
{% load thumbnail %}
<div>
{% for img in imgs %}
<div class="slide">
<li><img src="{% thumbnail img.image 480x312 crop,sharpen,quality=90 %}" alt=""></li>
<div class="caption" style="bottom:0">
<p>{{ img.caption }}</p>
</div>
{% endfor %}
</div>
Look at the example in the docs
You need to quote your geometry values:
<img src="{% thumbnail img.image '480x312' crop="center" quality="90" %}" alt="">

Plugin Context Processors in django-cms

I'm trying to get django cms' plugin context processors for my hooked app. I followed the documentation http://docs.django-cms.org/en/2.1.3/extending_cms/custom_plugins.html#plugin-context-processors , but for some reason it doesn't work. Here is a my sample context processor:
def test_context_processor(instance, placeholder):
print instance
return {'testkey':'testvalue'}
and my template:
{% load cms_tags %}
<!doctype html>
<head>
<title></title>
{% plugins_media %}
</head>
<body>
{% placeholder "main" %}
</body>
</html>
I added a text plugin in the main placeholder, and added the text {{testkey}}. It renders it as {{testkey}} instead of testvalue. The print statement in the context processor gets logged properly - meaning that the context processor is called for sure. I'm not sure what am I doing wrong here.
--- Edit ---
My settings file:
# -*- coding: utf-8 -*-
import os
gettext = lambda s: s
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#domain.com'),
)
MANAGERS = ADMINS
LANGUAGES = [('en', 'en')]
DEFAULT_LANGUAGE = 0
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(PROJECT_DIR, 'mycms.db'),
# }
#}
DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '***' # Or path to database file if using sqlite3.
DATABASE_USER = '***' # Not used with sqlite3.
DATABASE_PASSWORD = '***' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '5432' # 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 = '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
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/admin/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '0r6%7gip5tmez*vygfv+u14h#4lbt^8e2^26o#5_f_#b7%cm)u'
# 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.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.toolbar.ToolbarMiddleware',
'cms.middleware.media.PlaceholderMediaMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'cms.context_processors.media',
)
CMS_PLUGIN_CONTEXT_PROCESSORS = (
'helpdocs.cms_context_processors.test_context_processor',
)
CMS_TEMPLATES = (
('example.html', 'Example Template'),
)
ROOT_URLCONF = 'urls'
TEMPLATE_DIRS = (
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.admin',
'cms',
'menus',
'mptt',
'appmedia',
'south',
'cms.plugins.text',
'cms.plugins.picture',
'cms.plugins.link',
'cms.plugins.file',
'cms.plugins.snippet',
'cms.plugins.googlemap',
'helpdocs',
)
The Plugin Context Processors are used to process the context with which the templates of the plugin are rendered. They do not alter the content of any database field (in your case, 'body' on the Text model).
Therefore it will not replace anything in your text plugin. To do what you're trying to do, have a look at Plugin Processors (http://docs.django-cms.org/en/2.1.3/extending_cms/custom_plugins.html#plugin-processors) which allow you to process the rendered output of a plugin.
To achieve what you're trying to do you would do something like this:
def my_plugin_processor(instance, placeholder, rendered_content, original_context):
return rendered_content.replace('{{ testkey }}', 'testvalue')