There seems to be an issue with Django failing to load media files on a shared hosting platform utilizing

Struggling with loading user-uploaded media files and displaying them through a template.html file when DEBUG is set to FALSE. The static files are showing up fine, but every time I try to access the page, I keep encountering a 404 error for

webaddress/media/images/image1.png
. Even after following some suggested steps like adding
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
to my urls.py, the issue persists. Unfortunately, the cPanel hosting provider informed me that I can't modify the Apache httpd.conf file on cPanel, so now I'm exploring options to let Django handle the serving of these media files since it's responsible for image uploads to the media/images directory.

Location of the images directory:

/home/<cPanelUserName>/repositories/djangoApp/media/images

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
template/index.html

<body style="background: url('{{ background_pic.url }}'); background-size: cover; background-position: center; background-attachment: fixed;">
    <div id="profile">
        <img id="userPhoto" src="{{ profile_pic.url }}" alt="{{ profile_pic_title }}">
    </div>
</body>
models.py

class profilePic(models.Model):
    title = models.CharField(max_length=50)
    image = models.ImageField(upload_to='images/')

class backgroundPic(models.Model):
    title = models.CharField(max_length=50)
    image = models.ImageField(upload_to='images/')
views.py

def index(request):
    imageModel = profilePic.objects.get(pk=1)
    backgroundModel = backgroundPic.objects.get(pk=1)

    return render(
        request,
        "template/index.html",
        {
            "profile_pic_title":imageModel.title,
            "profile_pic":imageModel.image,
            "background_pic_title":backgroundModel.title,
            "background_pic":backgroundModel.image,
        }
    )
urls.py

from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('', include('SocialLinks.urls')),
    path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Answer №1

It can be beneficial to adjust your media root path to the public_html directory when working with shared hosting on cPanel.

Prior to this change, your media files may have been located within your project folder.

 MEDIA_ROOT = '/home/{username}/{project}/media' ✖️

Following the adjustment, your media files will now be stored inside the public_html directory.

 MEDIA_ROOT = '/home/{username}/public_html/media' ✔️

Answer №2

Not sure if this method will work for you, but it did the trick for my cPanel shared hosted Django Project. Here is the step-by-step procedure I followed (assuming DEBUG is set to False, and the server is apache):

Step 1: Update settings.py file

...
MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / 'media'
...

Step 2: Make changes in the root urls.py file

...
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [ 
 ...
 ...
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Step 3: Modify the .htaccess file (Explanation on where to find it below)

# Instructions for setting up .htaccess for CloudLinux Passenger configuration
PassengerAppRoot "/home/<username>/<site_directory_name>"
PassengerBaseURI "/"
PassengerPython "/home/<username>/virtualenv/<site_directory_name>/<python_version>/bin/python"

# Rewrite Engine Activation
RewriteEngine On

# Serve media files
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^media/(.*)$ /home/<username>/<site_directory_name>/media/$1 [L]
...

# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN

<IfModule Litespeed>
</IfModule>
# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION END

Remember to restart the server after making these changes.

This should hopefully resolve your issue. Explaining the code snippets:

Regarding Step #1, these are standard configurations for managing media files.

  • MEDIA_URL = 'media/' indicates that all media file URLs will start with media/ after the domain name. For example, if your domain is example.com and you have an image called my_image.jpg in a directory named post_images within the main media folder named media, the URL for the image would be

    https://example.com/media/post_images/my_image.jpg
    .

  • MEDIA_ROOT = BASE_DIR / 'media' signifies that there is a folder named media at the same level as the manage.py file in your project directory. This folder stores all the media files. If your media root directory has a different name, update

    MEDIA_ROOT = BASE_DIR / '<your_media_root_directory_name>
    .

For Step #2, these configurations allow the development server to serve media files.
In a development environment where DEBUG = True, when Apache server is not present, Django's default server serves media files. By adding this line with the conditional check, you instruct Django to handle media file serving. When DEBUG is not set to True, Apache web server manages this task.

As for Step #3, modifying the (.htaccess) file pertains to Apache configuration.

The .htaccess file can be found in the project directory. Since it is prefixed with a dot (.), it may be hidden by default in cPanel. You need to unhide all hidden files first if you plan to access it through the file manager. Otherwise, using terminal or a text editor like vim, locate it with the ls -a command. In the file manager, click on settings at the top of the window, enable the option for showing hidden files (dotfiles), then save to reveal the .htaccess file. Some code may already exist in it; simply replace it with the provided instructions.

This resolved my issue. While you may no longer require this assistance, someone else in a similar predicament might benefit from this solution if they stumble upon it in their search for answers.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

code for multiple custom fields in woocommerce

I followed a tutorial to incorporate multiple custom fields into the general tab of product post settings. After inputting data into the fields, it gets saved and displayed on the product page seamlessly; However, the issue arises when I delete this dat ...

Multer returns an undefined response

I am currently utilizing multer in my Node.js application to handle file uploads, along with AngularJS for the front end. However, when I click on the upload image button, I'm getting an undefined response in the console. Can someone assist me in reso ...

When converting HTML to PDF using Dompdf, Font Awesome icons may not appear as expected

I am currently using Dompdf for exporting an HTML page to PDF. The issue I am facing is that when the HTML file contains Font Awesome icons, in the resulting PDF there are question marks instead of the icons. Below is a snippet of the HTML code: <!DOC ...

Encountering difficulties with image file uploads in Django and AJAX due to CSRF issues

I experimented with Alex Kuhl's unique ajax script for uploading images to Django 1.4. The first thing that puzzles me is why I'm seeing a blank page and Firebug indicating an error: In my template html: $ is not defined element: $('#fil ...

Google's local host connection is currently being refused

Recently, as I was practicing HTML code to work on some forms, I encountered an issue when trying to run the code in the browser by pressing F5. Instead of seeing my code displayed, I received an error message that read: This site can’t be reached local ...

Creating a data structure using jQuery/JavaScript when submitting a form - a guide

Currently, I am attempting to gather form input values and organize them into an array of objects that will then be sent to MongoDB. However, I am facing difficulty in figuring out how to include an array within the objects (refer to the comment in the cod ...

Is it possible to incorporate a different website font into an email template?

Currently working on an email template and looking to match the font with my website. Is there a method to ensure my site's font carries over into the email template? Provided below is the HTML code: <!DOCTYPE html> <html> <head> ...

Steps to download a file once the submit button is clicked on an HTML webpage

I have a radio button in my application that displays file names from my Google Drive. My goal is to allow users to select a file and download it to their local device using the corresponding download URL. To achieve this, I utilize an HTTP GET request w ...

Guide to making a password input field for a user model in Django

I'm diving into Django for the first time. I'm working on my models.py file and want to include a User model to manage users who log in to the application. Adding fields like 'first_name = models.CharField(max_length=50', 'last_na ...

AngularJS Requesting Multiple Images

I'm currently in the process of building a new AngularJS application. Everything seems to be running smoothly, except for one issue with loading an image. In my view, I've included the following code: <img ng-src="img/views/portrait/{{emplo ...

The size of the Tweet button iframe is set at 107 pixels

Has anyone been able to successfully adjust the size of the tweet button generated by Twitter's iframe code? My attempts have resulted in a default width of 107px, but I need it to match the actual button size. I've tried adjusting the CSS proper ...

Switch between sliding elements to the right and to the left using JavaScript

I attempted to create a small header navigation bar for the search, language, and contact options (see demo below). All elements are clickable. However, I am having trouble getting the content to slide in, move the other icons, and slide back when another ...

Tips for importing font files from the node_module directory (specifically otf files)

We cannot seem to retrieve the fonts file from the node module and are encountering this error message. Can't find 'assets/fonts/roman.woff2' in 'C:\Projects\GIT2\newbusinessapp\projects\newbusinessapp\src ...

ModelForm is not very happy when it receives an instance

I'm currently trying to update a row in the Dog model using Django forms, but I keep encountering an error. The error message reads: __init__() got multiple values for keyword argument 'user' This issue seems to be stemming from this line ...

What is the best way to insert a page break only when necessary?

My code includes multiple dynamic tables within a div element: <div> <table> <tr></tr> <tr></tr> ... </table> <table> <tr></tr> <tr>< ...

Safari shows a contrasting outcome

Having an issue with compatibility in the safari browser You can check out the site here: The problem lies with the text inside the image, I want it to display properly like it does in Chrome. Here is the desired result for Safari as well. Below is the ...

Why did the bootstrap installation in my project fail?

Previously, everything on my website was functioning correctly. However, upon launching it now, I noticed that the carousel, buttons, and other elements are broken. It seems like there might be an issue with the Bootstrap CDN as the buttons and sliders are ...

Designing an accordion with the main content peeking out slightly before collapsing into place

Seeking assistance in creating an accordion that displays a snippet of content before collapsing. I'm facing difficulty starting this project. While a basic accordion is simple to implement, I am unsure how to show a portion of the content (such as t ...

Differences in rendering with Google Chrome when zooming in or out

After creating some code, I observed a peculiar issue. At 500% zoom, the DOWNLOAD button aligns perfectly with the left wall without any gap. However, upon reducing the zoom to 250%, a green background segment becomes visible. To witness this anomaly, refe ...

Discovering the precise Offset value for a Div element

Looking for a way to identify the unique value of each div on my HTML page, even as offset values change with each refresh. Any suggestions or methods that can help achieve this? ...