Search code examples
pythoncssdjangoazuredjango-staticfiles

Django Staticfiles not being served on Azure


I'm trying to deploy a simple Django web app to an Azure website. I'm using Python Tools for Visual Studio because I couldn't get any other way to remotely work. I'm having an issue where my template loads but none of staticfiles will load. I've created a folder called static and have updated settings.py as follows:

STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
STATIC_ROOT = ''
STATIC_URL = '/static/'

In my template (called index.html) which is stored in a templates folder also in the root, I refer to the files as follows: <img class='social' src="{% static 'VSpace/images/128-twitter.png' %}"/>

The page loads with plain HTML (no CSS or images) and in the browser's developer view I see that a 404 was returned when requesting the images and the rest of the static files.

I've searched for hours for a solutions and made all kinds of changes. Does anyone have any idea what I could be doing wrong?


Solution

  • On Azure web sites, python apps are hosted on IIS using FastCGI. With the preceding web.config configuration, all the requests are routed to the Django application. And using VS to deploy Django apps, the app folder and static folder are both in root folder. So we can manually configure IIS setting, here are my steps:

    1, I use VS to create a Django project, and I deploy on Azure Web app with default settings, they should be like the following:

    STATIC_ROOT = path.join(PROJECT_ROOT, 'static').replace('\\', '/') 
    STATIC_URL = '/static/'
    STATICFILES_DIRS = ()
    

    2, Logon in Kudu Console of your Web app via the format of URL

    https://<your_web_site_name>.scm.azurewebsites.net/DebugConsole
    

    , and access in the folder D:\home\site\wwwroot\static, type 'type nul>web.config' in command line to create a empty web.config file.

    3, Edit web.config copy3, Edit web.config copy the following code into the file, save and restart web site in Azure portal.

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <system.webServer>
        <!-- this configuration overrides the FastCGI handler to let IIS serve the static files -->
        <handlers>
        <clear/>
          <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="File" requireAccess="Read" />
        </handlers>
      </system.webServer>
    </configuration>
    

    And we can get more information in Running Django Under Windows With IIS Using FastCGI