[Fixed]-Detecting url scheme in settings.py of Django app

1👍

This can’t be done in settings.py file as it contains only constants and variables. It doesn’t process requests. But this can be done in a middleware.

Here’s a middleware in it’s simplest form to check URL scheme:

class DetectUrlScheme(object):
    """ Middleware for detecting URL scheme """

    def process_request(self, request):
        if request.is_secure():
            # HTTPS
            # do something ...
        else:
            # HTTP
            # do something ...
        return

Although, if you’ve got only a couple of views, writing a middleware seems an overhead. So, you can check URL scheme in your views, too.

def myview(request):
    if request.is_secure():
        # HTTPS
        # do something ...
    else:
        # HTTP
        # do something ...
👤xyres

Leave a comment