Django media files not loading when debug is False on Cpanel - django
I am trying to show my media files for over a week and tried all stackoverflow solutions yet nothing. My project is hosted on Cpanel, i tried giving the media the absolute path, tried to put them on the public_html folder, nothing. Plus my static files are served without issue, but the media files doesn't even show in the source in developer tools (in normal case there should be one there), when debug is true it works perfectly fine but when debug is false it does not. Any ideas please?
part of my settings.py
import os
from django.contrib.messages import constants as messages
from decouple import config
# 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/3.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
CSRF_COOKIE_SECURE = config('CSRF_COOKIE_SECURE')
SESSION_COOKIE_SECURE = config('SESSION_COOKIE_SECURE')
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',
'whitenoise.middleware.WhiteNoiseMiddleware'
]
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
CKEDITOR_UPLOAD_PATH = 'uploads/'
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
INTERNAL_IPS = ['127.0.0.1', '::1', '0.0.0.0']
project urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
path('panier/', include('cart.urls', namespace='cart')),
path('commande/', include('orders.urls', namespace='orders')),
path('ckeditor/', include('ckeditor_uploader.urls')),
path('coupon/', include('coupons.urls', namespace='coupons'))
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
if settings.DEBUG == True:
import debug_toolbar
urlpatterns += [path('__debug__/', include(debug_toolbar.urls)),]
some of my models
from django.db import models
from django.urls import reverse
from django.utils import timezone
import datetime
from django.db.models import F
from django.conf import settings
import os
from django.utils.deconstruct import deconstructible
from django.core.validators import MinValueValidator
from ckeditor.fields import RichTextField
from django.utils.safestring import mark_safe
PRODUCT_STATUS = (
('N', 'Nouveau'),
('P', 'Promotion'),
('S', 'Sans Status')
)
#deconstructible
class PathAndRename(object):
def __init__(self, sub_path):
self.path = sub_path
def __call__(self, instance, filename):
filename = 'product_{0}_{1}'.format(instance.user.id, filename)
# return the whole path to the file
return os.path.join(self.path, filename)
def solution_directory_path(instance, filename):
date_fields = str(datetime.date.today()).split('-')
year = date_fields[0]
month = date_fields[1]
day = date_fields[2]
# file will be uploaded to MEDIA_ROOT/solutions/YEAR/MONTH/DAY/solution_id_<filename>
solution_sub_path = 'solutions/{0}/{1}/{2}/solution_{3}_{4}'.format(year, month, day, instance.id, filename)
solution_full_path = os.path.join(settings.MEDIA_ROOT, solution_sub_path)
if os.path.exists(solution_full_path):
os.remove(solution_full_path)
return solution_sub_path
def product_directory_path(instance, filename):
date_fields = str(datetime.date.today()).split('-')
year = date_fields[0]
month = date_fields[1]
day = date_fields[2]
# file will be uploaded to MEDIA_ROOT/produits/YEAR/MONTH/DAY/produit_<produit_id>_<filename>
product_sub_path = 'produits/{0}/{1}/{2}/product_{3}_{4}'.format(year, month, day,instance.product_id, filename)
product_full_path = os.path.join(settings.MEDIA_ROOT, product_sub_path)
if os.path.exists(product_full_path):
os.remove(product_full_path)
return product_sub_path
def product_directory_path_second_picture(instance, filename):
date_fields = str(datetime.date.today()).split('-')
year = date_fields[0]
month = date_fields[1]
day = date_fields[2]
# file will be uploaded to MEDIA_ROOT/produits/YEAR/MONTH/DAY/produit_<produit_id>_<filename>
product_sub_path = 'produits/{0}/{1}/{2}/product_{3}_photo_2_{4}'.format(year, month, day,instance.product_id, filename)
product_full_path = os.path.join(settings.MEDIA_ROOT, product_sub_path)
if os.path.exists(product_full_path):
os.remove(product_full_path)
return product_sub_path
def product_file_directory_path(instance, filename):
date_fields = str(datetime.date.today()).split('-')
year = date_fields[0]
month = date_fields[1]
day = date_fields[2]
# file will be uploaded to MEDIA_ROOT/produits/YEAR/MONTH/DAY/produit_<produit_id>_<filename>
product_sub_path = 'fichers/{0}/{1}/{2}/product_{3}_{4}'.format(year, month, day,instance.product_id, filename)
product_full_path = os.path.join(settings.MEDIA_ROOT, product_sub_path)
if os.path.exists(product_full_path):
os.remove(product_full_path)
return product_sub_path
# custom product manager : have to use it for search filtering
class ProductManager(models.Manager):
def get_queryset(self):
return super(ProductManager, self).get_queryset()\
.filter(stock__gte=1, available=True)
class Solution(models.Model):
name = models.CharField( max_length=50)
slug = models.SlugField( max_length=70)
photo = models.ImageField(verbose_name='Photo de la solution', upload_to=solution_directory_path, blank=True)
photo_2 = models.ImageField(verbose_name='Photo 2 de la solution', upload_to=solution_directory_path, blank= True)
description = RichTextField(verbose_name='Text en plus', blank= True, null=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("produit", args=[self.slug])
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'Catégorie'
verbose_name_plural = 'Catégories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("product-by-cat", args = [self.slug])
class Product(models.Model):
product_id = models.CharField(max_length= 50, blank=False, null= False, unique=True, default='',verbose_name='Numéro du Produit')
name = models.CharField(max_length=50, verbose_name = 'Nom du Produit', db_index=True)
slug = models.SlugField(max_length=70, verbose_name= 'Slug')
solution = models.ForeignKey(Solution, on_delete=models.SET_NULL, verbose_name='Solution', default='', null=True)
category = models.ForeignKey(Category, on_delete= models.CASCADE, related_name="products" ,verbose_name='Catégorie')
sub_title = models.CharField(max_length=100, verbose_name=("Sous titre"), blank= True)
description = RichTextField(verbose_name='Description', blank= True, null=True)
sup_info = RichTextField(verbose_name='Informations Supplémentaires', blank= True, null=True)
photo = models.ImageField(verbose_name='Photo du Produit', upload_to= product_directory_path, blank=True)
photo_2 = models.ImageField(verbose_name='Photo du Produit 2', upload_to= product_directory_path_second_picture, blank=True)
file_1 = models.FileField(verbose_name='Fiche Technique', upload_to=product_file_directory_path, blank= True)
price = models.DecimalField(verbose_name='Prix', max_digits=10, decimal_places=2, validators = [MinValueValidator(0)], blank=False, null=False)
available = models.BooleanField(verbose_name='Disponibilité', default=True)
status = models.CharField(choices= PRODUCT_STATUS, max_length=50, default='S' , blank=False, null = False, verbose_name="Status")
created = models.DateTimeField(verbose_name='Date de Création', auto_now_add=True)
updated = models.DateTimeField(verbose_name='Date de dernière mise à jour', auto_now=True)
stock = models.PositiveIntegerField(verbose_name='Stock', validators= [MinValueValidator(0)], default=0, blank=False, null=False )
objects = models.Manager() # The default manager.
show = ProductManager() # Our custom manager
class Meta:
ordering = ('name',)
verbose_name = 'Produit'
verbose_name_plural = 'Produits'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("produits", args=[self.slug])
def get_description(self):
return mark_safe(self.description)
def get_sup_info(self):
return mark_safe(self.sup_info)
class ContactForm(models.Model):
name = models.CharField(verbose_name='Nom complet', max_length=100)
phone = models.CharField(verbose_name="Téléphone" , max_length=25)
email = models.EmailField(verbose_name="Email", null=True, blank = True)
subject = models.CharField(verbose_name="Sujet", max_length=50, blank=False)
message = models.TextField(verbose_name="Sujet", blank=False, null=False)
date_sent = models.DateTimeField(verbose_name="Date", auto_now_add=True)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Formulaire de Contact'
class Post(models.Model):
titre = models.CharField(max_length=200)
slug = models.SlugField(max_length=100)
intro = models.CharField(max_length=200, blank=True)
image = models.ImageField(verbose_name='Image' ,upload_to='slides/', blank= True)
text = RichTextField(verbose_name='Article', blank= True, null=True)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.titre
You can't use whitenoise to serve your media files: https://github.com/evansd/whitenoise/issues/62 You'll need to configure your server to have apache or nginx or something similar serve those media files from your media directory.
Related
Django admin models not showing in production
I've put my django project into production. Every time a add an admin model it does not update and show on my admin panel. The migrations and collectstatic commands are all going through fine. I have tried to source a fix but I just can't get it to work. Works completely fine in local server. Here is my code although: models.py class PostImage(models.Model): image = models.ImageField(null=False, blank=False, upload_to="images", default="default.png") image_title = models.CharField(max_length=100, null=False, blank=False, default="") def __str__(self): return self.image_title class BlogPost(models.Model): blog_title = models.CharField(max_length=255, null=True, blank=True) blog_article = QuillField(null=True, blank=True) blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") blog_date = models.DateField(auto_now_add=True) def __str__(self): return self.blog_title class EnterImage(models.Model): enter_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") enter_image_title = models.CharField(max_length=100, null=False, blank=False, default="") def __str__(self): return self.enter_image_title class QuillPost(models.Model): content = QuillField() def __str__(self): return self.content class AboutMe(models.Model): about_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") about_image_title = models.CharField(max_length=100, null=False, blank=False, default="") def __str__(self): return self.about_image_title urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', include('martinhensonphotography.urls')), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT) admin.py from django.contrib import admin from . models import PostImage, EnterImage, BlogPost, QuillPost, AboutMe # Register your models here. admin.site.register(PostImage) admin.site.register(BlogPost) admin.site.register(EnterImage) admin.site.register(QuillPost) admin.site.register(AboutMe) APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'martinhensonphotography.apps.MartinhensonphotographyConfig', 'crispy_forms', 'django_quill', 'ckeditor', 'ckeditor_uploader',
djano - can not display an uploaded image from mySQL database
I configured everything as it should and yet I can't display the images from my database. settings.py : STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) models.py class Etudiants(models.Model): numeroetudiant = models.BigIntegerField(db_column='numeroEtudiant', blank=True, null=True) # Field name made lowercase. nom = models.CharField(max_length=255, blank=True, null=True) prenom = models.CharField(max_length=255, blank=True, null=True) groupe = models.BigIntegerField(blank=True, null=True) photo = models.ImageField(blank=False, null=False, upload_to='images/') email = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'etudiants' def __str__(self): return self.nom + " " + self.prenom views.py : def ajoutetudiant(request): submitted = False if request.method == "POST": form = EtudiantsForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect("../ajoutetudiant/") else: form = EtudiantsForm() if 'submitted' in request.GET: submitted = True return render(request, 'ajoutetudiant.html', {'form': form}) urls.py (of my project) : from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('notes.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) .html : <img src="{{etudiant.photo.url}}"/> The pictures are saved in my database as you can see here. But cannot display it. My field in mySQL database is "blob". If it shouldn't be blob what should i put ?
Your MySQL field for photo should be: `photo` varchar(100) NOT NULL,
Failed - No file Downloading uploaded files in Django
I have a model here in Django in which an entity can have several uploaded files: from django.db import models from model_utils.models import TimeStampedModel from .managers import ProviderManager class Provider(TimeStampedModel): full_name = models.CharField('Nombre', max_length=100, unique=True) phone1 = models.CharField("Teléfono", max_length=50, blank=True, null=True) phone2 = models.CharField("Teléfono", max_length=50, blank=True, null=True) email1 = models.EmailField("Email", max_length=100, blank=True, null=True) email2 = models.EmailField("Email", max_length=100, blank=True, null=True) bank_info = models.TextField( "Info Banco", max_length=250, blank=True, null=True) objects = ProviderManager() class Meta: verbose_name = "Proveedor" verbose_name_plural = "Proveedores" ordering = ["full_name"] def __str__(self): return "Nombre: "+self.full_name def get_provider_files_names(self): provider_files = self.provider_files.all() file_list = [] for f in provider_files: # print(f.file.name.split('/')[-1]) file_list.append(f.file.name.split('/')[-1]) return file_list def get_provider_files_urls(self): provider_files = self.provider_files.all() file_list = [] for f in provider_files: file_list.append(f.file.url) return file_list class ProviderFiles(TimeStampedModel): file = models.FileField(upload_to="provider_files/%Y/%m/%d") provider = models.ForeignKey( Provider, on_delete=models.CASCADE, related_name='provider_files') class Meta: verbose_name = "Archivos Proveedor" verbose_name_plural = "Archivos Proveedores" def __str__(self): return "Nombre Proveedor: "+self.provider.full_name So then in my html I would like to access entity files and give the user links to download this files: <td> Download File </td> So then when download starts, it fails with error Failed - No file (file exists) Also important, if I access admin, and check uploaded files and open them, page says not found http://localhost:8000/media/provider_files/2021/02/24/Catalogo_2021_R0oiQHD.png
Adding the last line to main urls.py solved the problem: from django.contrib import admin from django.urls import path, re_path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), # users app re_path('', include('applications.users.urls')), re_path('', include('applications.home.urls')), re_path('', include('applications.clients.urls')), re_path('', include('applications.providers.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Django methodSerializer doesnt return absolute image url
Serializer.py class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ('id', 'post', 'post_img') class PostSerializer(serializers.ModelSerializer): postimg_set = serializers.SerializerMethodField('get_postimg_set') editor = UserSerializer() class Meta: model = Post fields = ('id', 'title', 'content', 'editor', 'postimg_set', 'created_at') def get_postimg_set(self, obj): a = PostImage.objects.filter(post = obj.id) print(a[0].post_img) return PostImageSerializer(a, many=True).data models.py from django.db import models import os, uuid, datetime from apps.account.models import * from django.utils import timezone def img_upload(instance, filename): ext = filename.split('.')[-1] now = datetime.datetime.now() path = "media/static/post/{}".format(instance.post.id) format = uuid.uuid4().hex + "_" + filename return os.path.join(path, format) class Post(models.Model): title = models.CharField('제목', null=False, blank=False, max_length=40) content = models.TextField('내용', null=False, blank=False) editor = models.ForeignKey(User, default = 1, null=False, blank=False, verbose_name="작성자", on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.localtime()) class Meta: verbose_name = '게시글' verbose_name_plural = '게시글' def __str__(self): return self.title class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) post_img = models.ImageField(upload_to=img_upload) class Meta: verbose_name = "게시글 이미지" verbose_name_plural = "게시글 이미지" def __str__(self): return str(self.post.title) + "이미지" Guess postimg_set = serializers.SerializerMethodField('get_postimg_set') is not return absolute URL for the images. When I use UserSerializer(), it returned absolute image url of User's profile image. Looking for help. Thank you
In your urls.py, Add: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -- closed--
Filtering with DjangoFilterBackend does not found the url
I'm using Django rest framework 3.8.2. I have read api-guide/filtering and followed the given example for the DjangoFilterBackend section. models.py class Pregunta(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=512, null=False) descripcion = models.CharField(max_length=200, null=False) categoria = models.ForeignKey(Pregunta_Categoria, on_delete=models.PROTECT) tipoRespuesta = models.ForeignKey(TipoRespuesta, on_delete=models.PROTECT, related_name='fk_id_tipoRespuesta') #sacar el default privated = models.BooleanField(default=False) status = models.CharField(max_length=1, default='A') created_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='proy_created_by8') created_on = models.DateTimeField(default=timezone.now) modified_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='proy_modified_by8') modified_on = models.DateTimeField(blank=True, null=True) class Meta: permissions = ( ('view_pregunta', 'View Pregunta'), ) def __str__(self): return "%s" % (self.name) def __unicode__(self): return u'%s' % (self.name) views.py class PreguntaViewSet(viewsets.ModelViewSet): queryset = Pregunta.objects.filter(estado='A') serializer_class = PreguntaSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('name', 'privated') Here is my serializer: class PreguntaSerializer(serializers.ModelSerializer): nom_tipoRespuesta = serializers.CharField( source="tipoRespuesta.nombre", required=False, allow_blank=True) class Meta: model = Pregunta fields = ( 'id', 'name', 'descripcion', 'categoria', 'tipoRespuesta', 'created_by', 'created_on', 'modified_by', 'modified_on', 'status', 'privated', 'nom_tipoRespuesta', ) urls.py from django.conf.urls import url, include from rest_framework import routers from proy import views router = routers.DefaultRouter() router.register(r'questions', views.PreguntaViewSet) router.register(r'questionCategories', views.PreguntaCategoriaViewSet) router.register(r'projects', views.ProyectoViewSet) router.register(r'polls', views.EncuestaViewSet) router.register(r'questionnaire', views.CuestionarioViewSet) router.register(r'pollByUser', views.EncuestaPorUsuarioViewSet) router.register(r'answerType', views.TipoRespuestaViewSet) router.register(r'answers', views.RespuestaViewSet) router.register(r'answerByUser', views.RespuestaPorUsuarioViewSet) router.register(r'variablesType', views.TipoVariableViewSet) router.register(r'variablesCategory', views.CategoriaVariableViewSet) router.register(r'variables', views.VariableViewSet) urlpatterns = [ url(r'^', include(router.urls)), ] settings.py: REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ), 'DEFAULT_PERMISSION_CLASSES': ( #'rest_framework.permissions.IsAuthenticated', ), 'EXCEPTION_HANDLER': 'adm.exceptions.core_exception_handler', 'NON_FIELD_ERRORS_KEY': 'error', 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', ), } However, when I try the url http://example.com/api/questions?name=someName&privated=True I get the error Page not found (404). What am I doing wrong?
By default the URLs created by DefaultRouter are appended with a trailing slash, try this url: http://example.com/api/questions/?name=someName&privated=True