Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make HttpResponse print the new line?

def index(request):
    review = Review.objects.all()
    output = "\n".join([each_review.review_text for each_review in review])

    return HttpResponse(output)

The output which I get is

"This book 1 is very great This book 2 is very great This book 3 is very great This book 4 is very great This book 5 is very great This something is very great"

But it doesn't print the new line between them. How to make that happen just with HttpResponse?

like image 799
InQusitive Avatar asked Oct 03 '17 11:10

InQusitive


2 Answers

By default HttpResponse has "text/html" as content-type, and html ignores newlines chars (or more exactly treats them as whitespaces).

If you want a text/html response content, you'll have to replace newlines by the appropriate html markup (either using <br> instead of newlines or wrapping each line in a <div> or <p> etc). You'll also need to wrap the whole thing into a proper html document, IOW adding the parent <html> and <body> tags around your content etc.

Else if a plain text content type is ok, just set the content-type header on your response:

return HttpResponse(output, content_type="text/plain")

so the browser knows to interpret and render it correctly.

As a side note: the way you're using both the orm and str.join() is vastly inefficient.

First, str.join() takes any iterable (as long as all the items are strings) so you don't need to build a list - you could just use a generator expression ie (notice the lack of brackets around the expression):

output = "\n".join(each_review.review_text for each_review in review)

But if you're only interested in a single field from the model, loading the whole fields and building a model instance is a complete waste of resources both at the database and python code levels. The solution here is to use a QuerySet.value_list() instead (here with the flat flag set to True since we only want a single field):

output = "\n".join(Review.objects.values_list("review_text", flat=True))
like image 123
bruno desthuilliers Avatar answered Nov 14 '22 06:11

bruno desthuilliers


you get a html so you should to use <br>

 output = "<br>".join([each_review.review_text for each_review in review])

or <pre>

 output = "\n".join([each_review.review_text for each_review in review])
 output = "<pre>{}</pre>".format(output)
like image 6
Brown Bear Avatar answered Nov 14 '22 04:11

Brown Bear