Django deployment

Hello,

I have deployed my django website to a linux and seems to be working fine, except for one thing. I have a download button on my site which lets someone get a copy of my CV (rtf file). This feature was working through out building the site however stopped workig as soon as I tried to con figure it with apache. Do text files have to be configured diffrently?

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf

        Alias /static /home/bashaar/rp-portfolio/static
        <Directory /home/bashaar/rp-portfolio/static>
          Require all granted
        </Directory>

Alias /uploads /home/bashaar/rp-portfolio/uploads
        <Directory /home/bashaar/rp-portfolio/uploads>
          Require all granted
        </Directory>

        <Directory /home/bashaar/rp-portfolio/personal_portfolio>
          <Files wsgi.py>
            Require all granted
          </Files>
        </Directory>

        WSGIScriptAlias / /home/bashaar/rp-portfolio/personal_portfolio/wsgi.py
        WSGIDaemonProcess django_app python-path=/home/bashaar/rp-portfolio python-home=/home/bashaar/rp-portfolio/venv
        WSGIProcessGroup django_app

</VirtualHost>

If anyone can point me to the right direction to look, it would be much appreciated.

Thanks

Welcome @Shab00 !

Side note: When posting code here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted. (I’ve taken the liberty of fixing your original post for you.)

No. They’re handled like any other file.

What directory does this file reside in?

What is the url that you are using to reference this file?

What is showing in the apache logs for the requests for this file?

Hi,

The file is BashaarCV.rtf and resides in the static folder:

Screenshot 2024-04-25 at 21.27.49

in views.py I am using the download function to call and process the document like this:

def download(request):
    file = os.path.join(settings.BASE_DIR, 'static/BashaarCV.rtf')

    fileOpened = open(file, 'rb')

    return FileResponse(fileOpened)

the urls.py:

from django.urls import path 

from pages import views

from django.contrib import admin


urlpatterns = [
    path("", views.home, name='home'),
    path("pages/templates/pages/contact", views.contact, name='contact'),
    path("pages/templates/pages/about", views.about, name='about'),
    path("static", views.download, name="static"),
]

when clicking the button the error message I get is:

[Thu Apr 25 20:36:00.854237 2024] [autoindex:error] [pid 77887:tid 140490477311552] [client 90.193.197.146:52662] AH01276: Cannot serve directory /home/bashaar/rp-portfolio/static/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm) found, and server-generated directory index forbidden by Options directive, referer: http://77.68.30.88/

Also the CSS styling on my admin pages seems to be missing. they are funtioning fine when it comes to uploading images and photos. these are all in my uploads folder… but should this be called media?

Reading some of documentation and watching some people online configuring there sites and i feel I have done it right… but evedently not.

also I have a base.html instead a index.html. Would that cause problems?

thanks

So I think I might of figured out my problem I haven’t succesfully run collecticstatic. but don’t understand why the styling on the rest of the site is working?

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS= [

        os.path.join(BASE_DIR, 'static')
]

I think I have done this wrong but will start to read the documentation, hope I am not looking into the wrong thing.

What is your STATIC_ROOT setting?

Include How to use Django with Apache and mod_wsgi | Django documentation | Django in your reading list.

Hi Ken,

My STATIC_ROOT is:

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

I did not have this set to anyhting which was the start of my problems. I also found that installing white noise would help with serving these static files.

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',
]

running collectstatic worked and all of the files was collected to the newly created staticfiles directory, however running the site I got an apache error that the site was not working anymore with an internal server error of:

[Sat Apr 27 10:12:05.966505 2024] [wsgi:error] [pid 108887:tid 139650218161728] [remote 90.193.197.146:58308] ModuleNotFoundError: No module named ‘whitenoise’

I am thinking STATIC_ROOT should be set diffrently like:

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

will try that next and read up more also might be the apache config file is wrongly configured and should be pointing to ‘staticfiles’ dir?

thanks

With a properly configured system, you don’t “need” to use Whitenoise.

Everything is in How to deploy Django | Django documentation | Django

But briefly:

  • STATIC_URL: Defines now urls are generated using the {% static ... %} tag. Needs to match a path defined by your web server for serving static files.

  • STATIC_ROOT: Defines the target directory where collectstatic is going to copy all static files. Needs to match the physical path configured in your web server for the logical path defined for STATIC_URL. Should be completely outside your project directory. Needs to be able to be read by the web server.

  • STATICFILES_DIRS: Defines additional directories beyond the static directories in your installed apps from which to find files for collectstatic to copy. Normally used to define the static directory at the project level.

Hi Ken,

Thanks for that, I would have been looking down that whitenoise rabbit hole if you didnt say that.

So I have had some success, where I have configured correctly and the styling on the admin pages are back. however still no luck with the download button.

django_project.conf

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf

        Alias /robots.txt /path/to/mysite.com/static/robots.txt
        Alias /favicon.ico /path/to/mysite.com/static/favicon.ico

        Alias /static /home/bashaar/rp-portfolio/staticfiles
        <Directory /home/bashaar/rp-portfolio/staticfiles>
          Require all granted
        </Directory>

        Alias /uploads /home/bashaar/rp-portfolio/uploads
        <Directory /home/bashaar/rp-portfolio/uploads>
          Require all granted
        </Directory>

        <Directory /home/bashaar/rp-portfolio/personal_portfolio>
          <Files wsgi.py>
            Require all granted
          </Files>
        </Directory>

        WSGIScriptAlias / /home/bashaar/rp-portfolio/personal_portfolio/wsgi.py
        WSGIDaemonProcess django_app python-path=/home/bashaar/rp-portfolio python->
        WSGIProcessGroup django_app

</VirtualHost>

Reading the doc on the site I feel I have configured settings.py correctly

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

and I feel I have loaded and deployed the static files correctly on my html page

<!-- pages/templates/pages/home.html -->


{% extends "base.html" %}

<a href="{% url 'home' %}"></a>

{% block page_content %}

<body>
    {% load static %}
    <div id="page-wrap">


        <img src="{% static 'images/BashaarBW.jpg' %}" alt="Photo of Bashaar" id="pic">

        <h1 class="fn">Bashaar Dhoot</h1>

        <div id="contact-info" class="vcard">
        
            <!-- Microformats! -->
        
           
        
            <p>
                Tel: <span class="tel">+447940 161 559</span><br />
                Email: <a class="email" href="mailto:bashaardhoot@gmail.com">bashaardhoot@gmail.com</a>
            </p>
        </div>
                
        <div id="objective">
            <p>
                Coming from a family of doctors, I&#39;ve naturally gravitated towards technologies that can help individuals in the
                healthcare sector. For my dissertation I created a Tumour detection application using MATLAB, taking stock
                images of MRI scans to identify tumours in the brain. I built a system where a user was able to upload an
                image and, using &#39;for-loops&#39;, highlight the tumorous area. I was pleased with the outcome, having successfully
                created a user-friendly application for people to self-identify possible brain tumours. Given the opportunity to
                continue the programming for the application I believe it would be possible to develop it to accurately detect
                tumours before they would become harmful to the individual.
            </p>
        </div>
        
        <div class="clear"></div>
        
        <dl>
            <dd class="clear"></dd>
            
            <dt>Education</dt>
            <dd>
                <h2>The Open University</h2>
                <p><strong>Major:</strong> Computing and ICT<br />
                   <strong>Minor:</strong>UX Design</p>
            </dd>
            
            <dd class="clear"></dd>
            
            <dt>Skills</dt>
            <dd>

                <h2>Computer skills</h2>
                <p>Python, Matlab, HTML, CSS, Microsoft productivity software (Word, Excel, etc), Adobe Creative Suite, Windows</p>
            
                <h2>Office skills</h2>
                <p>Office and records management, database administration, event organization, customer support, travel coordination</p>
                
            </dd>
            
            <dd class="clear"></dd>
            
            <dt>Experience</dt>
            <dd>
                <h2>The Open Univertsy <span>Student - London - 2019-2022</span></h2>
                <ul>
                    <li>Created an application that recognises Tumors in MRI Scans</li>
                    <li>Coordinated with staff and students to create an Open Universty sports website</li>
                    <li>Used Onlie fourums to create diffrent concepts for applications used in other students porjects</li>
                </ul>
                
                <h2>The City of London <span>Ranger - Hampstead Heath - present</span></h2>
                <ul>
                    <li>Overall management of the site</li>
                    <li>Managing stock for all employees working in different areas</li>
                    <li>Managing all sports &amp; recreational activities in the Extension</li>
                </ul> 
            </dd>
            
            <dd class="clear"></dd>
            
            <dt>Hobbies</dt>
            <dd>Application Design, Machine Learning Projects, Website Design</dd>
            
            <dd class="clear"></dd>
            
            <dt>References</dt>
            <dd>Available on request</dd>
            
            <dd class="clear"></dd>
        
        
        </dl>
        
        <div class="clear"></div>
        
        <div class="centerButton">
    
                
            <a href="{% url 'static' %}" download="BashaarCV.rtf">
              <button class="buttonCV" type="button">Download CV!</button>
            
            </a>
        </div>  

    </div>

</body>


{% endblock page_content %}

so still don’t unserstand why the styling on the page renders but my rtf file will not download? I have read the ‘staticfiles’ DIR should not be at root level?

thanks