#python #django #image #storage #cloudinary
Вопрос:
У меня есть модель профиля и модель поста. Когда режим отладки установлен в значение False, изображения не отображаются.
Вот мой settings.py
from pathlib import Path
import os
import dj_database_url
import cloudinary_storage
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.environ.get('SECRET_KEY', '...')
DEBUG = os.environ.get('DEBUG', False)
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'django.contrib.sitemaps',
'cloudinary_storage',
'taggit',
'tinymce',
'ckeditor',
'sweetify',
'hitcount',
'storages',
'notifications',
'django_resized',
'django_countries',
'post',
'website',
'comment',
'announce',
'superadmin',
'commissions',
'sitemanagement',
'profil.apps.ProfilConfig',
]
CLOUDINARY_STORAGE = {
'CLOUD_NAME': os.environ.get('CLOUD_NAME', 'name'),
'API_KEY' : os.environ.get('API_KEY', 'key'),
'API_SECRET' : os.environ.get('API_SECRET', 'secret'),
}
DEFAULT_FILE_STORAGE = os.environ.get('DEFAULT_FILE_STORAGE', 'cloudinary_storage.storage.MediaCloudinaryStorage')
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'club.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 = 'club.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': os.environ.get('ENGINE', 'django.db.backends.postgresql'),
'NAME': os.environ.get('NAME', 'name'),
'USER': os.environ.get('USER', 'user'),
'HOST': os.environ.get('HOST', 'host'),
'PASSWORD': os.environ.get('PASSWORD', 'password'),
'PORT': os.environ.get('PORT', 'port'),
}
}
db_from_env = dj_database_url.config(conn_max_age=600)
DATABASES['default'].update(db_from_env)
"""
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_USE_LOCALTIME = True
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', 'email_address')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_USER', 'email_password')
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'fr-fr'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = 'collectstatic/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static/')
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'static')
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
PASSWORD_RESET_TIMEOUT_DAYS = 1
HITCOUNT_HITS_PER_IP_LIMIT = 0
LOGIN_URL = 'login'
COUNTRIES_FIRST = [
'CI',
'BF',
'ML',
'BJ',
'DE',
]
DJANGO_NOTIFICATIONS_CONFIG = {
'USE_JSONFIELD' : True,
'SOFT_DELETE' : True,
'NUM_TO_FETCH' : 30,
'PAGINATE_BY' : 30,
}
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full',
# 'height': 300,
'width': 600,
'upadate' : [["Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker"],
['NumberedList', 'BulletedList', "Indent", "Outdent", 'JustifyLeft', 'JustifyCenter',
'JustifyRight', 'JustifyBlock'],
["Image", "Table", "Link", "Unlink", "Anchor", "SectionLink", "Subscript", "Superscript", 'update', 'HorizontalRule', 'Smiley', 'SpecialChar'], ['Undo', 'Redo'], ["Source"],
["Maximize"]],
},
}
CKEDITOR_UPLOAD_PATH = os.path.join(BASE_DIR, 'static/media/ckeditor/')
CKEDITOR_BROWSE_SHOW_DIRS = True
post_models.py
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from hitcount.models import HitCount
from django.contrib.contenttypes.fields import GenericRelation
from ckeditor_uploader.fields import RichTextUploadingField
from django_resized import ResizedImageField
from taggit.managers import TaggableManager
from notifications.signals import notify
from django.db.models.signals import post_save
# Post model
class Post(models.Model):
hit_count_generic = GenericRelation(HitCount,
object_id_field='object_pk',
related_query_name='hit_count_generic_relation'
)
author = models.ForeignKey(User, on_delete=models.DO_NOTHING,
null=True, blank=True, verbose_name='Auteur')
title = models.CharField(max_length=255, verbose_name='Titre')
slug = models.SlugField(unique=True,
verbose_name="Lien d'accès", max_length=400)
picture = ResizedImageField(
size=[500, 500],
quality=100,
default='assets/images/blog.png',
upload_to='media/images/posts/%Y/%m/',
verbose_name='Image principale')
content = RichTextUploadingField(verbose_name='Contenu')
tags = TaggableManager()
is_public = models.BooleanField(default=True,
verbose_name='Public')
resume = models.CharField(max_length=500,
verbose_name="Résumé")
picture_2 = ResizedImageField(
size=[500, 500],
quality=100,
default='assets/images/blog.png',
upload_to='media/images/posts/%Y/%m/',
verbose_name='Image secondaire 1')
picture_3 = ResizedImageField(
size=[500, 500],
quality=100,
default='assets/images/blog.png',
upload_to='media/images/posts/%Y/%m/',
verbose_name='Image secondaire 2')
is_popular = models.BooleanField(default=False,
verbose_name='Populaire')
date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now_add=True, null=True,
verbose_name='Mis à jour')
class Meta:
verbose_name='Publication'
verbose_name_plural = 'Publications'
def __str__(self):
return str(self.title)
def get_absolute_url(self):
return reverse('post-detail', kwargs={
"id" : self.id,
"slug" : self.slug,
})
# Send notifications if announce created
def send_post_notif(sender, instance, created, **kwargs):
verb_msg = f"""
Nouvelle publication: {instance.title}
"""
desc = f"""{instance.resume}n
Accèdez au menu 'Blog' pour la lire.
"""
if created:
if instance.is_public:
notify.send(instance,
recipient=User.objects.all(),
verb=verb_msg,
level='info',
description=desc)
post_save.connect(send_post_notif, sender=Post)
Profile_models.py
from django.db import models
from django_resized import ResizedImageField
from django_countries.fields import CountryField
from django.contrib.auth.models import User, Group, AnonymousUser
SEX_CHOICES = (
('masculin', 'masculin'),
('féminin', 'féminin')
)
class Profil(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
country = CountryField(null=True, blank=True, verbose_name='Pays')
sex = models.CharField(max_length=8, null=True, verbose_name='Sexe',
blank=True, choices=SEX_CHOICES)
date = models.DateTimeField(auto_now_add=True)
bio = models.TextField(null=True, blank=True,
verbose_name='Biographie')
is_author = models.BooleanField(default=False, verbose_name='Auteur')
signup_confirmation = models.BooleanField(default=False,
verbose_name="Confirmation d'activation du compte")
picture = ResizedImageField(
size=[225, 225],
quality=100,
default='assets/images/profile_default.png',
upload_to='images/profils/%Y/%m/')
class Meta:
verbose_name = 'Profil'
verbose_name_plural = 'Profils'
def __str__(self):
return f"Profil: {self.user.username}"
Я не знаю, почему не появляются изображения!
На самом деле, когда я создаю нового пользователя, изображение по умолчанию не отображается, а при создании нового поста изображения больше не появляются. Я не знаю, написал ли я что-то не так или что-то пропустил.
Можете ли вы помочь мне решить эту проблему, пожалуйста ???