I'm trying to upload an image via ajax. The image uploads well, but it is delivered inside a "None" folder, between the MEDIA_ROOT value and upload_to parameter of ImageField.
My current settings are as follows:
MEDIA_ROOT = (os.path.join(BASE_DIR, 'static', 'media'))
Inside my app's models.py:
image = models.ImageField(blank=True, null=True, upload_to=get_image_path)
and
def get_image_path(instance, filename):
return os.path.join(connection.tenant.schema_name, 'img', 'devices', filename)
When I upload the image, it goes to static/media/None/(tenant.schema_name)/img/devices, instead of static/media/(tenant.schema_name)/img/devices
(In the picture, tenant.schema_name is "ars")
The form is as follows:
class DeviceForm(ModelForm):
class Meta:
model = Device
fields = ['name', 'model', 'serial', 'location', 'note', 'image', 'page', 'address']
And the saving snippet:
if request.method == 'POST':
post_data = request.POST.dict()
form = DeviceForm(post_data, request.FILES)
if not form.is_valid():
return JsonResponse({"message": "Form is invalid"}, status=400)
obj = form.save()
return JsonResponse(obj.to_dict(), safe=False)
Is there a configuration that I'm missing? Any help would be appreciated
EDIT: Here's the whole settings.py:
import os
from django.utils.translation import ugettext_lazy
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = (key)
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
if DEBUG:
ALLOWED_HOSTS = ['*'] # Allow any host during debug mode
else:
ALLOWED_HOSTS = []
# Application definition
SHARED_APPS = [
'tenant_schemas',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 'cloud_admin',
'cloud_core',
]
TENANT_APPS = [
'django.contrib.contenttypes',
'django.contrib.auth',
'cloud_core.users',
'cloud_data',
'cloud_apps.dashboard',
'cloud_apps.device',
'cloud_apps.device_pages.kr',
# 'cloud_apps',
]
INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'ArsCloud.middleware.TenantSelectionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'ArsCloud.middleware.LoginRequiredMiddleware',
]
ROOT_URLCONF = 'ArsCloud.urls_public'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, "templates"),
os.path.join(BASE_DIR, "cloud_core", "templates"),
os.path.join(BASE_DIR, "cloud_admin", "templates"),
os.path.join(BASE_DIR, "cloud_data", "templates"),
os.path.join(BASE_DIR, "cloud_apps", "dashboard", "templates"),
os.path.join(BASE_DIR, "cloud_apps", "device", "templates"),
os.path.join(BASE_DIR, "cloud_apps", "device-pages", "templates"),
os.path.join(BASE_DIR, "cloud_apps", "device-pages", "kr", "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',
'cloud_core.context_processors.tenant'
],
},
},
]
WSGI_APPLICATION = 'ArsCloud.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
(database)
}
DATABASE_ROUTERS = (
'tenant_schemas.routers.TenantSyncRouter',
)
# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Language support
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale/')
]
LANGUAGES = (
(u'ja', ugettext_lazy('Japanese')),
(u'en', ugettext_lazy('English'))
)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
# STATICFILES_DIRS = [
# os.path.join(BASE_DIR, "static"),
# ]
STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static_root')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static', 'static_dirs'),
)
MEDIA_ROOT = (os.path.join(BASE_DIR, 'static', 'media'))
MEDIA_URL = '/static/media/'
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
LOGIN_EXEMPT_URLS = [
"upload_device_data"
]
TENANT_MODEL = 'cloud_core.Tenant'
DEFAULT_FILE_STORAGE = 'tenant_schemas.storage.TenantFileSystemStorage'
PUBLIC_SCHEMA_URLCONF = 'ArsCloud.urls_public'
ADMIN_SCHEMA_URLCONF = 'ArsCloud.urls_admin'
TENANT_SCHEMA_URLCONF = 'ArsCloud.urls_tenant'
ARSUSER_SCHEMA = "ars"
POST_TOKEN_KEY = {'key': (key), 'iv': "Salt for hashing"}
DUMMY_DB_PATH = os.path.join(BASE_DIR, 'falsedb')
DUMMY_DB_FILE = os.path.join(DUMMY_DB_PATH, 'config.json')
I used the config suggested by the answer below, but I still have a "None" folder between MEDIA_ROOT and the upload_to parameter
You should define media dir in settings.py file. images and files that you want to upload from website, store in media dir.
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static_root')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static', 'static_dirs'),
)
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')
MEDIA_URL = '/media/'
you need static directory inside of your project. Tree directory is like this:
static -
|-static_root
|-static_dirs
|-media
please create these 4 directories: static, static_root, static_dirs, media
Create media and static as folders both at the same level in your overall project directory (the same level as manage.py) and then try:
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(PROJECT_DIR)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
The media and static folders are used for two completely different things and media should never be nested inside static. The media folder is for user-uploaded content, and the MEDIA_ROOT you define is where user-uploaded content is uploaded to (with sub-folders within MEDIA_ROOT being set via upload_to=.....). The static folder and (and sub-folders) hold content that you define as part of the website (e.g. css, js).
I would also make this small change (no need for request.POST.dict()):
if request.method == 'POST':
form = DeviceForm(request.POST, request.FILES)
Related
I am doing a project for college this was my first app with django I have no prior experience to this
I am trying to deploy my app to heroku, I deployed it a couple of hours back with "DISABLE_COLLECTSTATIC" config and it was working. When I tried adding the static files settings the app was not working anymore, it still deploys but I get the "Application Error" when i open the app.
This is settings.py
import os
from pathlib import Path
import dj_database_url
from django.contrib.messages import constants as messages
import mimetypes
development = os.environ.get('DEVELOPMENT', False)
MESSAGE_TAGS = {
messages.DEBUG: 'alert-secondary',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY', '')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = development
# Application definition
INSTALLED_APPS = [
# My apps
'learning_logs',
'users',
# Default apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'cloudinary_storage',
'django.contrib.staticfiles',
'cloudinary',
'bootstrap4',
'tinymce',
'crispy_forms',
]
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 = 'online_journal.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'templates', 'allauth'),
[TEMPLATES_DIR],
],
'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 = 'online_journal.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
if development:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
else:
DATABASES = {
'default': dj_database_url.parse(os.environ.get('DATABASE_URL'))
}
if development:
ALLOWED_HOSTS = ['localhost']
else:
ALLOWED_HOSTS = [os.environ.get('HEROKU_HOSTNAME')]
# Password validation
# https://docs.djangoproject.com/en/3.2/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/3.2/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/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'))
STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CSRF_TRUSTED_ORIGINS = ['online-journal2022.herokuapp.com']
LOGIN_URL = 'users:login'
# Cloudinary Settings
CLOUDINARY_STORAGE = {
'CLOUD_NAME': '', # I removed these for safety
'API_KEY': '',
'API_SECRET': '',
}
mimetypes.add_type("text/css", ".css", True)
I tried changing staticfiles_dirs because it seemed that the path to the staticfiles is wrong, the collectstatic command did not work, i hardcoded the staticfiles_dirs and then collectstatic worked, but heroku didn't, so i reverted the changes, I deleted the cloudinary settings at the bottom that resulted in an error so i reverted that change as well, the current output i am getting n heroku is this.
I uploaded my whole site in my live server after uploading django admin is not showing any design before uploading it was fine but after upload in it got like this :-
Here is my settings.py I think I did all the thing perfectly but still :( I tried so many time and I got stuck here almost 2 days :) I hope someone will help me with this problem.
Settings.py
"""
Django settings for gng project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
# 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/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$tl4x!&*01z(0o2r&la&e#)f0dz0x)^bov7dh^aau$m#shktiw'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['gngbd.xyz', 'www.gngbd.xyz']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'store',
]
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 = 'gng.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 = 'gng.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
DEBUG = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static'] # Main Line #
STATIC_ROOT = os.path.join(BASE_DIR, 'static/css/')
STATIC_ROOT = os.path.join(BASE_DIR, 'static/js/')
STATIC_ROOT = os.path.join(BASE_DIR, 'static/fonts')
STATIC_ROOT = os.path.join(BASE_DIR, 'static/admicss')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = "images/"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, 'staticfiles'))
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'gngxyz/static'),
)
I think you have to run following command to collect all static files in one place:
python manage.py collectstatic
then press ctrl+F5. I hope this solves your problem.
And check if you have following in your settings.py:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, 'staticfiles'))
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
In addition to collecting your static files, in some web servers you have to reconfigure location of your static files. For example in nginx you have to add the following :
location /static {
autoindex on;
alias /direction/to/your/static;
}
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.
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
I am learning Django and have built a sample Django app. It works fine on my computer, but I am having trouble deploying it to Heroku.
My root directory has the following structure:
My setttings.py file has the following settings for static files:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
The full settings.py file is following:
"""
Django settings for firstdjango project.
Generated by 'django-admin startproject' using Django 1.8.
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 = 'j8s(6fw61+cx_o=g!9a(vs!wbj0&f!7u_lw$(eap5d4li#!b4('
# SECURITY WARNING: don't run with debug turned on in production!
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',
'inventory',
)
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.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'firstdjango.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['firstdjango/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 = 'firstdjango.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'),
}
}
# 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/
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age = 500)
DATABASES['default'].update(db_from_env)
# STATIC_URL = '/static/'
# STATICFILES_DIRS = [
# os.path.join(BASE_DIR, "static")
# ]
# STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
When I try to deploy to Heroku, I get the following error message:
ImproperlyConfigured:You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
Here are the recommended settings for static root for a django -> heroku project
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, 'static'),
]
I would recommend just using this https://github.com/heroku/heroku-django-template as a starting point and import your apps into that project. Due to the fact (as of now) that Heroku recommends using the following packages
Gunicorn
WhiteNoise
dj-database-url
The git project will provide you with "Production-ready configuration for Static Files, Database Settings, Gunicorn, etc." In other words, it will give you the correct configuration to deploy Django to Heroku.