Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print the value of a variable in Python/Django?

Tags:

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?

like image 589
Joren Avatar asked Oct 11 '12 20:10

Joren


People also ask

How do you print the value of a variable in Python?

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.

How do you print variable names and values in Python?

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.

Can you print in Django?

Yes, you can print directly to a printer from Django (or any web app) using this method.


1 Answers

<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

like image 156
Joran Beasley Avatar answered Oct 04 '22 09:10

Joran Beasley