Django static media not showing picture - python

after searching for a solution for hours which did not resolve my problem,I am posting this. The image from my media root is not showing up on my html. In chrome's console i get a 404 file not found.Even though the image is there. I am using Python 3 ,Django 1.10 in Pycharm.
This is the model which is where i upload images to:
from django.db import models
class Post(models.Model):
username = "anonymous"
post = models.ImageField(upload_to='anon')
creation_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return Post.username
views.py:
from django.shortcuts import render,get_object_or_404
from .models import Post
def home(request):
return render(request,"base.html",{})
def post_detail(request,id=None):
instance = get_object_or_404(Post,id=id)
context = {
"post": instance.post,
"instance": instance
}
return render(request,"post_detail.html",context)
post_detail.html(here the image isnt showing):
<body>
<img src = "{{ instance.post.url}}" height="520" width="500"><br>
{{ instance.creation_date }}<br>
{{ instance.username }}<br>
</body>
Parts of setting.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Post',
]
MIDDLEWARE = [
'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',
]
ROOT_URLCONF = 'Post.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'debug': DEBUG,
'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 = 'Post.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'Post/media/')
What my directories look like:

It's a common mistake to mix up the static and media settings. In your case what you are actually dealing with is user uploaded MEDIA and not STATICs.
<img src = "{{ instance.post.url}}" height="520" width="500"><br>
The settings that are most relevent are MEDIA_* settings described here
https://docs.djangoproject.com/en/1.10/howto/static-files/
But more importantly, in your dev sever you need to enable the delivery of MEDIA by adding
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Related

Django static file problem. Clicking on the files downloads

sorry for my bad english.
My index.html file cannot find the files in the static folder. When I view the page source, I click on the css file and I get different errors from time to time. Sometimes I get 404 error when I click on css link. Sometimes when I click on the css file, it downloads the file.
Settings.py:
import os
from pathlib import Path
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'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',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates/")],
'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',
],
},
},
]
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',
},
]
LANGUAGE_CODE = 'tr'
TIME_ZONE = 'Europe/Istanbul'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Urls.py:
from django.conf import settings
from django.conf.urls import static
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
from django.conf.urls.static import static
urlpatterns = [
path('', include("home.urls"), name="anasayfa"),
path('admin/', admin.site.urls)
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
index.html:
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
Important: I'm doing my first env project, can there be a problem with the installation?
add this STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] in settings.py before STATIC_ROOT = os.path.join(BASE_DIR, '/static/')

Django: form is valid but is not save because no module named app is found

I'm developing a simple form to upload files. I'm using Django 2.2.3.
I see that my form is valid because some print statments I've made, however I'm getting an error when saving the form.
ModuleNotFoundError at /admineditorial/predica/add/
No module named 'app'
And:
Exception Location: <frozen importlib._bootstrap> in _find_and_load_unlocked, line 965
I don't think it has to do something with Bootstrap. I don't know what could be happening.
Also, I'm uploading to /audio, but do I need to create this folder or is it generated automatically? if not, where should I create it?
Proyect structure:
-editorial
|_managment.py
|_migrations.py
|_templates
|_editorial
|_index.html
|_predicas
|_predicas.html
|_base.html
|_admin.py
|_forms.py
|_models.py
-el_comercio_app
|___init__.py
|_settings.py
|_storage_backends.py
|_urls.py
|_wsgi.py
models.py:
class Predica(models.Model):
audio_file = models.FileField(upload_to = u'audio/', max_length=200)
views.py:
# Create your views here.
def predica_upload(request):
predicas = Predica.objects.all()
if request.method == 'POST':
form = PredicaUpload(request.POST, request.FILES)
if form.is_valid():
print("### Form is valid ###")
form.save()
print("Despues del save")
print(form)
return redirect('today_editorial')
else:
print("### Form not valid ###")
print(form.errors)
else:
form = PredicaUpload()
return render(request, 'predicas/predicas.html', {'form': form, 'predicas': predicas})
urls.py:
from django.urls import path
from editorial import views
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin', admin.site.urls),
path("", views.today_editorial, name="today_editorial"),
path('predicas',views.predica_upload, name = 'predica_upload')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
predicas.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<button type="submit">Subir</button>
</form>
{% for predica in predicas %}
<div>
<img src="{{predica.audio_file.url}}" alt="myvideo">
</div>
<p>No audios in my gallery yet :-(</p>
{% endfor %}
settings.py:
"""
Django settings for el_comercio_app project.
Generated by 'django-admin startproject' using Django 2.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
from decouple import config
from dj_database_url import parse as dburl
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
ALLOWED_HOSTS = ['127.0.0.1', 'el-comercio-editoriales.herokuapp.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'editorial',
'storages'
]
MIDDLEWARE = [
'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',
]
ROOT_URLCONF = 'editorial.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'editorial', 'templates/'),]
,
'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',
'django.template.context_processors.media'
],
},
},
]
WSGI_APPLICATION = 'el_comercio_app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
# SECURITY WARNING: don't run with debug turned on in production!
default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3')
DATABASES = { 'default': config('DATABASE_URL', default=default_dburl, cast=dburl), }
####
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',
},
]
LANGUAGE_CODE = 'es-PE'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'
####
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')
####
AWS_LOCATION = 'static'
AWS_ACCESS_KEY_ID ='XXXXXX'
AWS_SECRET_ACCESS_KEY = 'XXXXXXXXXXXXXXXXXXXX'
AWS_STORAGE_BUCKET_NAME ='universidad-elim-test-videos'
AWS_S3_CUSTOM_DOMAIN='%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
DEFAULT_FILE_STORAGE = 'app.storage_backends.MediaStorage'
STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_URL='https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
AWS_DEFAULT_ACL = None
UPADTE 1
I had a file apps.py but deleted it bacuse maybe it was causing a conflict. However, it did not solve the problem.
apps.py:
from django.apps import AppConfig
class EditorialConfig(AppConfig):
name = 'editorial'
In your INSTALLED_APPS your app should be listed like this:
INSTALLED_APPS = [
...,
'editorial.apps.EditorialConfig'
]
You can read in the docs
First of all in your settings.py the ROOT_URLCONF is pointing to 'editorial.urls' but in your project structure I don't see the urls.py second in the error your are posting is talking about admineditorial/ directory and i don't see it in your project structure neither.

Django Displaying Images Not Found

This has been driving me crazy for 2 days now and I cannot find an answer to this. I have looked through countless posts and cannot get this to work.
I am trying to display a profile picture for a user using Django ImageField in my model.
For some reason it keeps on coming up with 404 not found, even though I can see that the path to the image file is correct.
For example:
My model:
class KPILead(models.Model):
name = models.CharField(max_length=255)
position = models.CharField(max_length=255)
company = models.ForeignKey(KPICompany)
profile_pic = models.ImageField(upload_to='profile_pics/')
def __str__(self):
return self.name
This is indeed uploading the image file to the media/profile_pics folder in my root directory.
The view:
#login_required(login_url='/')
def eftlead_detail(request, eftlead_id):
context = dict()
context['eftlead'] = KPILead.objects.get(pk=eftlead_id)
context['team_names'] = KPITeam.objects.filter(eft_lead__id=eftlead_id)
context['incidents'] = KPIIncidentReport.objects.filter(eft_lead__id=eftlead_id)
context['image_url'] = context['eftlead'].profile_pic.url
return render(request, 'templates/eftlead.html', context)
The static and media settings in my settings file:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
And I have added:
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
to my urls file.
It just gives an error of 404 not found, even when I check the source in Chrome or Firefox I can see that correct path is being shown. If I try and click on the image in the source to go to http://127.0.0.1:8000/media/profile_pics/default.jpg I get an error of 404 not found, so Django is clearly not finding the file even though the path is correct.
As I said I have struggling with this for 2 days now and is probably the last thing I need to finish this project off, but I cannot understand what is going wrong.
I would happy to provide further information if required and thank you for any help.
EDIT: I have included my full settings file.
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'q#-jd#zkg7+#2-=6pjy(%vg-%=sh%c1*c%ypu&uxz0-4cm-9^p'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
USE_DJANGO_JQUERY = 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',
'base.apps.BaseConfig',
'projects.apps.ProjectsConfig',
'kpi.apps.KpiConfig',
'smart_selects'
]
MIDDLEWARE = [
'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',
]
ROOT_URLCONF = 'gregweb.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates', 'kpi'],
'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 = 'gregweb.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase'
}
}
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Africa/Johannesburg'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
LOGIN_REDIRECT_URL = '/kpi'
LOGOUT_REDIRECT_URL = '/'
Add this in your project's urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #not both

Ckeditor/ django 2.0 admin body input disappeared

I recently installed Ckeditor on django 2.0, turns out some of the css and js files are not loading properly, I manage to get Ck read the files but now my admin body input was disappeared. missing-admin-body
As I am pretty new to django, I was wondering if I were doing anything wrong in the setting. (try to make a blog, url + generic view set up)
setting.py
>
INSTALLED_APPS = [
'personal',
'blog',
'contact',
'widget_tweaks',
'ckeditor',
'ckeditor_uploader',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'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',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'EST'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_DIR = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URLS = '/media/'
# sendmail setting
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DEFAULT_FROM_EMAIL = 'kai.peng#uconn.edu'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
EMAIL_PORT = 1025
#CKeditor meida.root, and other setting
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_BASEPATH = "{% static 'ckeditor/ckeditor/' %}"
CKEDITOR_FILENAME_GENERATOR = 'utils.get_filename'
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_JQUERY_URL = os.path.join(STATIC_URL,'js/jquery.min.js')
CKEDITOR_CONFIGS = {
'awesome_ckeditor': {
'toolbar': 'Basic',
},
}
here is my blog/url.py
>
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post
from django.urls import re_path, path
urlpatterns = [
path('', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:25],
template_name="blog/blog.html")),
path('blog/<pk>/', DetailView.as_view(
model = Post,
template_name="blog/post.html")),]
And here is my blog/views.py
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post
from django.urls import path, re_path
from django.shortcuts import render
urlpatterns = [
path(r'', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:25],
emplate_name="blog/blog.html")),
path('blog/<int:id>/', DetailView.as_view(
model = Post,
template_name="blog/post.html")),
]
And this is my model.py
>
from django.db import models
from ckeditor.fields import RichTextField
class Post(models.Model):
title = models.CharField(max_length = 140,null = True)
body = RichTextField(config_name='awesome_ckeditor')
date = models.DateTimeField(null = True)
name = models.CharField(max_length=128,null = True)
def __str__(self):
return self.title
this is the console view when I tried to refresh admin edit page
console view
I am using a python 3.6X and Django 2.0, on a Windows platform.
here is the website response with the 'empty body' site response
I suspect theres problem on the db integration or model registration, not sure....
admin.py
from django.contrib import admin
from blog.models import Post
admin.site.register(Post)
# Register your models here.
In my case it was about installing required plugins, I added following line to CKEDITOR_CONFIGS but I forgot to download these plugins and put them inside static folder
'extraPlugins': ','.join(['codesnippet', 'prism', 'widget', 'lineutils', 'clipboard']),
I also specified plugin directories like this:
CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/"
BTW make sure plugin folder's name inside this directory is the same with plugin's name, as you download plugins as zip and then extract it, its name can be a bit different...
This was all I have done to fix my issue.

Why does Django raise "KeyError"?

I am currently trying to implement pagination to my Django web app. However, when I try to use template tags from the library, Django raises a key error. To be specific:
KeyError
KeyError: 'request'
Here is my settings.py:
from django.core.urlresolvers import reverse_lazy
from os.path import dirname, join, exists
import os
# Build paths inside the project like this: join(BASE_DIR, "directory")
BASE_DIR = dirname(dirname(dirname(__file__)))
STATICFILES_DIRS = [join(BASE_DIR, 'static')]
MEDIA_ROOT = join(BASE_DIR, 'media')
MEDIA_URL = "/media/"
# Use Django templates using the new Django 1.8 TEMPLATES settings
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
join(BASE_DIR, 'templates'),
# insert more TEMPLATE_DIRS here
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven't customized them:
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# Use 12factor inspired environment variables or from a file
import environ
env = environ.Env()
# Ideally move env file should be outside the git repo
# i.e. BASE_DIR.parent.parent
env_file = join(dirname(__file__), 'local.env')
if exists(env_file):
environ.Env.read_env(str(env_file))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.auth',
'django_admin_bootstrapped',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'authtools',
'crispy_forms',
'easy_thumbnails',
'geoposition',
'bootstrap_pagination',
'profiles',
'accounts',
'clients',
)
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 = 'saas.urls'
WSGI_APPLICATION = 'saas.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL = '/static/'
ALLOWED_HOSTS = []
# Crispy Form Theme - Bootstrap 3
CRISPY_TEMPLATE_PACK = 'bootstrap3'
# For Bootstrap 3, change error alert to 'danger'
from django.contrib import messages
MESSAGE_TAGS = {
messages.ERROR: 'danger'
}
# Authentication Settings
AUTH_USER_MODEL = 'authtools.User'
LOGIN_REDIRECT_URL = reverse_lazy("profiles:show_self")
LOGIN_URL = reverse_lazy("accounts:login")
THUMBNAIL_EXTENSION = 'png' # Or any extn for your thumbnails
The template-tag I am trying to run is:
{% block pagination %}
{% bootstrap_paginate page_obj range=10 show_prev_next="false" show_first_last="true" %}
{% endblock %}
What to do?
The bootstrap_paginate template tag expects your template context to contain the request variable. Make it available by changing your context_processors to:
'context_processors': [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven't customized them:
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'django.contrib.auth.context_processors.request', # <-- Here we add the request
],
if you have imported
import django_heroku
Then put this:
django_heroku.settings(local())
in the end of your settings.py file

Categories