1

For some reason I am in need of a views.py that returns only some text. Normally, i'd use HttpResponse("text") for this. However, In this case I require the text to be send over https, to counter the inevitable mixed content warning.

What is the simplest way of sending pure text via django(1.7.11) over https?

Mitchell van Zuylen
  • 3,905
  • 4
  • 27
  • 64
  • Is a view required for this? I've done this kind of thing for things like google verification URLs directly like this: url(r'google\.html$', lambda r: HttpResponse("google-site-verification: google.html", content_type="text/plain")). Not sure if this will work in your case. – rob Dec 05 '17 at 21:24
  • 1
    This question appears to be based on a fundamental misunderstanding. HttpResponse doesn't specify that the response is sent over HTTP; the view - and in fact Django itself - has nothing to do with the method of communication with the client, that is entirely the responsibility of the server. – Daniel Roseman Dec 06 '17 at 11:20
  • @DanielRoseman Thank you, there was indeed a misunderstanding. This means that the original question "simplest way of sending text over https" would simply be HttpResponse? – Mitchell van Zuylen Dec 06 '17 at 14:30

2 Answers2

0

I've run into the mixed content problems as well. From my experience, you simply can't use the HttpResponse objects without running into trouble. I was never totally sure though and eventually found a way "around" it.

My solution for it was to use the JsonResponse object instead, to return JSON strings, kind of a work-around with the views returning something like:

mytext = 'stuff blablabla'
return JsonResponse({'response_text': mytext})

Which is super easy to parse, and OK with HTTPS. Maybe not what you're looking for, but I hope it helps you find your way.

S_alj
  • 447
  • 1
  • 3
  • 15
0

Django in the relevant docs of httprequest.build_absolute_uri reads:

Mixing HTTP and HTTPS on the same site is discouraged, therefore build_absolute_uri() will always generate an absolute URI with the same scheme the current request has. If you need to redirect users to HTTPS, it’s best to let your Web server redirect all HTTP traffic to HTTPS.

The docs make clear that

the method of communication is entirely the responsibility of the server

as Daniel Roseman commented.

My prefered choice is to force https throughout a site, however it is possible to do it only for a certain page.

The above can be achieved by either:

There are also other -off the road- hackish solutions like a snippet which can be used with a decorator in urls.py to force https, or a custom middleware that redirects certain urls to https.

raratiru
  • 8,748
  • 4
  • 73
  • 113