简体   繁体   中英

Django how to use multiple lines with return HttpResponse

I just picked up Django a couple days ago and I don't have much experience with any languages other than java, so Python is a bit of a learning curve. I manages to create a web page that generates a random number each time you refresh it and tells you whether or not it is the number one.

当前

The problem lies in using multiple lines on a single page. Instead of having the page look like that, I want it to be formatted vertically, like this:

点击

n = random.randint(1, 2)  # returns a random integer
if n == 1:
    query = "The number is One."
else:
    query = "The number Is'nt One."
return HttpResponse(str('Randomly generated number: ') + str(n) + str("   ") + str(query))

One thing I noticed is that all the code after "return HttpResponse" is unused, for example if I had moved the "if" and "else" statements to after the HttpResponse, it would be marked as unused code and would not appear on the final product.

Learn about Python and Django a little more. HttpResponse is a quick and dirty way that output is done in views. You can learn about how use Templates for this, you can read about this in:

https://docs.djangoproject.com/en/1.9/intro/tutorial03/

and use Templates for your process.

Just use <br/> where you want the break line. When browser finds the <br/> changes line.

n = random.randint(1, 2)  # returns a random integer
if n == 1:
    query = "The number is one."
else:
    query = "The number isn't one."
return HttpResponse('Random Number Generator <br/> The random number is: ') + str(n) + "<br/>" + query)

I think the best solution would be to set content_type="text/plain" :

n = random.randint(1, 2)  # returns a random integer
if n == 1:
    query = "The number is One."
else:
    query = "The number Isn't One."
output_string = "Randomly generated number: \n The random number is: " + str(n) + "\n" + query
return HttpResponse(output_string, content_type="text/plain")

The default content type of HttpResponse is text/html ( docs ), so using <br> would work. However, this essentially creates a non-valid HTML page. Thus, for such simple output, I think text/plain is the best choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM