Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Django to use HTTPS URLs when reversing

I am running my Django application in Cloud9 for development purposes using the usual ./manage.py runserver. But to the outside world, the app is accessible via a https:// URL.

The problem is that when I use the URL reverse function, the URLs that come back start with http:// (at least some of the time). When I try redirecting to one of those URLs, I get an error like this one in the console:

Mixed Content: The page at 'https://apps.facebook.com/xxxx/' 
was loaded over HTTPS, but requested an insecure form action 
'http://xxxx.c9users.io/facebook_app/gift_shop/'. 
This request has been blocked; the content must be served over HTTPS.

My question: is there a way to force reverse to generate HTTPS URLs instead of HTTP?

Here is a snippet of code, which has problems with redirection from HTTPS URLs to HTTP ones:

class IndexRedirectView(RedirectView, CSRFExemptMixin):
    permanent = False

    def get_redirect_url(self, *args, **kwargs):
        if self.request.user.visit_count >= 5:
            return reverse('gift-shop')
        if len(BaseGiftableInstance.objects.filter(giving_user=self.request.user)) > 0:
            # has won something
            return reverse('gift-shop')
        return reverse('spinner')
like image 962
Magnus Teekivi Avatar asked Feb 04 '16 12:02

Magnus Teekivi


2 Answers

If you are on Django 1.8 or greater, you can force SSL with the setting SECURE_SSL_REDIRECT = True - see this answer on a similar question

like image 176
nthall Avatar answered Sep 30 '22 11:09

nthall


You should check out django-sslify, you just install it and add it to your MIDDLEWARE_CLASSES.

like image 38
cowlicks Avatar answered Sep 30 '22 12:09

cowlicks