Django + Zinnia: Can not GET image for entry's illustration - python

I'm using Django (1.7.3) with zinnia blog (0.15.1) and I'm having an issue for rendering the 'image for illustration' that you can add for a blog entry.
I have the following urls.py files:
My top-dir url conf
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^ecv/', include('extended_cv.urls',namespace="ecv")),
url(r'^weblog/', include('zinnia.urls', namespace='zinnia')),
url(r'^comments/', include('django_comments.urls')),
)
The settins.py file:
# -*- coding: utf-8 -*-
** Snip**
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
# For using django.contrib.sites
SITE_ID = 2
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pro',
'extended_cv',
'zinnia', # Added for zinnia blog usage
'django.contrib.sites',# Added for zinnia blog usage
'django_comments',# Added for zinnia blog usage
'mptt',# Added for zinnia blog usage
'tagging',# Added for zinnia blog usage
)
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',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'zinnia.context_processors.version',
)
** Snip**
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
When I create an entry for zinnia using admin UI, and when I add an image, no error appear, and the new entry is saved to database with no warning. The image then appear in the server tree file at the adress TopDir/upload/zinnia/date/of/publication/index_IKd2N0d.jpeg
But, when I read the new entry from the weblog app, I correctly see the new entry, but not the image. Moreover, the server output the following error:
GET /weblog/2015/01/18/1st-entry/uploads/zinnia/2015/01/18/index_IKd2N0d.jpeg HTTP/1.1" 404 8922
I guess the issue is kind of complicated to debug, then if you need more information, I'll be happy to give you more.
Thank you.

As explain by Daniel Roseman in the comments, the answer consists into defining the variables MEDIA_URL and MEDIA_ROOT, and to rewrite the top urls.py file as explained in https://docs.djangoproject.com/en/1.7/howto/static-files/#serving-files-uploaded-by-a-user-during-development:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^ecv/', include('extended_cv.urls',namespace="ecv")),
url(r'^weblog/', include('zinnia.urls', namespace='zinnia')),
url(r'^comments/', include('django_comments.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And the work is done.

Related

Django - Not Found The requested resource was not found on this server on Production

I was trying to deploy my Django project on Render . Everything works fine except for the media files. I can't figure out the issue here.
I have added the followings into my settings.py:
DEBUG=False
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
]
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',
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
]
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [
BASE_DIR / "static"
]
MEDIA_URL = '/contents/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/contents/')
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage"
urls.py
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
I have created a Post (using models) before deploying. It had an image located a ./static/contents/Screenshot_334.png After deploying this image is accessible at https://someusername.onrender.com/static/contents/Screenshot_334.png . But if I create a new post from the deployed site I get a 404 error. The site doesn't cause any issue while its in the development mode.
Here's a portion of LOGS from Render:
https://someusername.onrender.com/static/contents/Screenshot_334.png (created while development) is accessible but https://someusername.onrender.com/static/contents/Screenshot_1.png (created post-production) is inaccessible. Also, static files (css, js) working fine.
I checked all the files and directories using the following piece of code:
res = []
for path, subdirs, files in os.walk('./'):
for name in files:
res.append(os.path.join(path, name))
Screenshot_334.png and Screenshot_1.png both are in the same directory
I also tried switching MEDIA_URL and MEDIA_ROOT to 'contents', 'contents/', 'static/contents/' and all the possible variations.
UPDATE:
I have found a workaround since I couldn't figure it out myself. I have mapped media to the urls.py and used FileResponse
Here's how views.py looks:
from django.http import FileResponse
def media(request, path:None):
img = open('./contents/'+path, 'rb')
response = FileResponse(img)
return response
I'm aware this might cause security issues but I think it won't do me any harm since it is a project just for learning.
Add whitenoise in your installed apps
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'whitenoise',
'accounts',
]
then add whitenoise.middleware.WhiteNoiseMiddleware in your middleware right after the first line.
try configring the static files as below in your settings.py
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [
BASE_DIR / "static"
]
MEDIA_URL = 'contents/'
MEDIA_ROOT = BASE_DIR / 'static/contents'
edit your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path(....)
]
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT
)

Django settings and view mapping error

I have build a realtime notification app using Django(1.8.5). I am using django server, Nodejs as push server, ishout.js[nodejs+redis +express.js API]. So I installed them by following the instructions.
Kindly suggest how this error can be fixed :
settings.py file
"""
#Django settings for realtimenotif project.
Generated by 'django-admin startproject' using Django 1.8.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gvvs-0*-cohfbm#()*nyt&0u!77sc_8vnw%1afpkmhi&y-6&ds'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ADMINS = (
#'arunsingh','arunsingh.in#gmail.com'
)
MANAGERS = ADMINS
ALLOWED_HOSTS = ["*"]
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'drealtime',
'sendnotif',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'drealtime.middleware.iShoutCookieMiddleware',
'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',
)
ROOT_URLCONF = 'realtimenotif.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'realtimenotif.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#The following settings are not used with sqlite3:
'USER':'',
'PASSWORD':'',
'HOST':'', # Empty for localhost through domain sockets,127.0.0.1
'PORT':'', # Set to empty string for default
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/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.8/howto/static-files/
STATIC_URL = '/static/'
urls.py file
"""realtimenotif URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import patterns, include, url
#from sendnotif.views import home, alert
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(['',
url(r'^$', 'sendnotif.views.home', name='home'),
#url(r'^$', home, name='home'),
url(r'^alert/$', 'sendnotif.views.alert', name='alert'),
#url(r'^alert/$', alert, name='alert'),
url(r'^accounts/login/$','django.contrib.auth.views.login',name='login'),
#uncomment the next line to enable the admin:
url(r'^admin/$', include(admin.site.urls)),
] )
Django server is starting, it says works and gives this message
"You're seeing this message because you have DEBUG = True in your
Django settings file and you haven't configured any URLs. Get to
work!"
What changes I have to make in my settings.py and views.py file, Kindly suggest pointers to workaround. I have gone through official django documentation and beginner tutorials, but to no rescue.
You can see the project source code at githubRepo
Django fails to find your urls.py file.
You need to point the root URLconf at the realtimenotif.urls module. Create a top level urls.py and use an include(), eg:
yoursite/urls.py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^/', include('realtimenotif.urls')),
url(r'^admin/', include(admin.site.urls)),
]
or alternatively move your urls.py from realtimenotif to the top level folder.

Django Flatpages DB Tables Not Created

Ubuntu 14.04
Python 3.4.0
Django 1.7
I just followed the 4 step directions to set up flatpages, but when I ran python3 manage.py migrate, none of the DB tables for the flatpages were created. All the other tables were created, just not the ones needed to flatpages. I'm pretty puzzled by this, 'cause this isn't complicated. I added the right stuff into my settings.py --
SITE_ID = 1 # added for flatpages
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites', # added
'django.contrib.flatpages.urls', # added for flatpages
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', #added
)
...and into my urls.py (though I don't think this could affect DB table creation) --
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
url(r'^$', 'pets.views.home', name='home'),
url(r'^pages/', include('django.contrib.flatpages.urls')),
url(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt',
content_type='text/plain')),
url(r'^admin/', include(admin.site.urls)),
)
...am I having a brain fart or something? I don't see why this won't work, but it's just not creating the DB tables needed for flatpages. This isn't my 1st time creating something with Django, but it is my 1st time trying out flatpages.
Yes, probably a brain fart: you've added the urls module to INSTALLED_APPS, rather than the app itself.
'django.contrib.flatpages', # added for flatpages

django - Page not found (404)

this is my first django app and I Have received the following msg:
Page not found (404)
Request Method: GET
Request URL:
Using the URLconf defined in _3Ms.urls, Django tried these URL patterns, in this order:
^ ^$ [name='vista_principal']
^admin/doc/
^admin/
The current URL, home/, didn't match any of these.
my setting.py
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media/')
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
)
# 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 = '7th)hsx0w5mwlv+oty62w(us7&xtiw#y0&12)67ld%6y1-a)4f'
# 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 = '_3Ms.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = '_3Ms.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'apps',
)
_3Ms/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', '_3Ms.views.home', name='home'),
# url(r'^_3Ms/', include('_3Ms.foo.urls')),
url(r'^', include('apps.es.urls')), # incluye las urls de es.urls.py
# 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)),
)
es/urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns('apps.es.view',
url(r'^$', 'home_view', name='vista_principal'),
)
es/views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
def home_view(request):
return render_to_response('es/home.html', context_instance=RequestContext(request))
You don't have a url for home/.
If you added url(r'^home/$', 'home_view', name='vista_principal'), it would have something to go to.

Django 1.4.1 not loading admin site (Django Book tutorial)

I can't figure out why Django is not loading the admin page. It seems like it isn't even reading the urls.py file that I am editing - because even if I comment out the 'urlpatterns' statement, it still loads the local hello page fine once I run the server.
This is the error message:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/admin
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^hello/$
^time/$
^time/plus/(\d{1,2})/$
The current URL, admin, didn't match any of these.
This is my urlpatterns code:
from django.conf.urls import patterns, include, url
from mysite.views import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
('^hello/$', hello, ),
('^time/$', current_datetime, ),
(r'^time/plus/(\d{1,2})/$', hours_ahead, ),
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.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))
)
And this is a snippet os my settings.py file:
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 = (
'/Users/pavelfage/Desktop/Coding/mysite/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',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'mysite.books'
)
Any help much appreciated!
I faced same problem. Uncommenting from django.contrib import admin in urls.py solved the problem.
I had the same problem. You may try this:
In your urls.py replace the call include(admin.site.urls) by this: admin.site.urls
In your setting.py if don't have any TEMPLATE_CONTEXT_PROCESSORS property (that was my situation) add this:
TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.contrib.messages.context_processors.messages")
It seams to be roughly the default property in a normal django 1.4 configuration. Here are the docs talking about it: djangoproject-doc1 djangoproject-doc2
You may also have to uncomment the strings:
# 'django.contrib.messages',
# 'django.contrib.staticfiles',
in your INSTALLED_APPS property of the settings.py but i'm not sure about it.
Sorry about not explaining much better the reasons of those changes but I'm a django-beginner to. I just found your question corresponding to my problem and then a possible awnser.
I hope it may help you.
EDIT: as seen in a comment you may try to remove the url(...) instruction on the line concerning the url of the admin site
ben

Categories

Resources