William Shaw
William Shaw

Reputation: 180

Serve static HTML in Django

I’m pretty new to Django so forgive me if this is something I shouldn’t even consider, but I’d like my app to be able to link to a large number of static HTML pages (enough that creating URL paths to each one would be unreasonable) and there would constantly be more being uploaded (by me via FTP).

I’ve got this working on the the development server by adding the path to those HTML files to my STATICFILES_DIRS [] but that doesn’t seem to work when I push my code to production.

I tried setting up a STATIC_ROOT and running collectstatic but that didn’t help, and I’m also worried that even if I got that working, I would have to run collectstatic each time I uploaded new files.

So my question is, is this even reasonable? Should I just avoid hosting these static HTML files alongside my project and leave them where they are now, on a separate server under a separate domain?

The only reason I wanted to host them together initially is because along with the static HTML files, there is an SQL LITE database that my Django app displays data from (this is the whole purpose of my app). However, I could just implement another method of getting that SQL LITE file like using ftlib. Note that I don’t need that database to connect to Django at all - I just needs to read data from it.

Upvotes: 3

Views: 2277

Answers (1)

xyres
xyres

Reputation: 21834

You don't need to write urls for every page. You can "capture" the requested page name from the url and render the page according to its value.

# urls.py
url(r'^page/(?P<page_name>\w+)/$', my_view)


# views.py
import os
from django.http import HttpResponse, Http404

FTP_UPLOAD_DIR = '/path/to/directory/where/you/upload/files/'


def my_view(request, page_name):

    # check if requested page exists
    if os.path.exists(FTP_UPLOAD_DIR + page_name):
        # if yes, then serve the page
        with open(FTP_UPLOAD_DIR + page_name) as f:
            response = HttpResponse(f.read())
        return response

    else:
        raise Http404

Above, we are reading the file directly from the upload folder, so there's no need for you to run collectstatic.

Upvotes: 3

Related Questions