In PHP I'm used to being able to do print $var
or print_r($var)
.
I can print variables in my views in python but they end up in my cmd window not on the page itself. This is fine for some things but windows' cmd window isn't exactly the most readable when it starts wrapping output and turning it into gibberish.
I tried doing {% print somevar %}
in the django template, but I get TemplateSyntaxError: Invalid block tag: 'print'
So, for someone who's new to Python how do I easily see the value of a variable?
You first include the character f before the opening and closing quotation marks, inside the print() function. To print a variable with a string in one line, you again include the character f in the same place – right before the quotation marks.
Using f-strings in Python to print variables is the most commonly used method and I would personally recommend using this method. In this method, an 'f' is placed before the opening quotation mark of a string. Braces {} are placed around the names of variables that you are looking to print.
Yes, you can print directly to a printer from Django (or any web app) using this method.
<html> {{ this_is_my_variable_that_is_passed_to_my_view }} </html>
the {{
allow variable access to the item which will call the items __unicode__
function if it exists otherwise it will call its __str__
function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With