[Django]-Serve static HTML in Django

3👍

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.

👤xyres

Leave a comment