Reputation: 763
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.
Upvotes: 0
Views: 3683
Reputation: 964
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.
Upvotes: 1
Reputation: 2058
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.
Upvotes: 0
Reputation: 7242
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)
Upvotes: 0