Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel's dd() equivalent in django

I am new in Django and having a hard time figuring out how to print what an object have inside. I mean type and value of the variable with its members inside. Just like Laravel's dd(object) function. Laravel's dd() is a handy tool for debugging the application.

I have searched for it. But found nothing useful. I have tried pprint(), simplejson, print(type(object) and {% debug %}. But none of them could provide the required information about an object. Here is a sample output from Laravel's dd() function. enter image description here

In this Image, I am printing the request object of Laravel. as you can see its showing complete information about an object. I mean name of class it belongs to, its member variables. also with its class name and value. and it keeps digging deep inside the object and prints all the information.

But I am not able to find a similar tool in Django. That's hard to believe that Django doesn't have such a useful tool. Therefore I would like to know about any third party package that can do the trick.

I am using Django version 2.0.5. and trying to print django.contrib.messages

Also, I want the output to be displayed in the browser, not in the console. In a well readable way that's why I am asking for a Django package that can take in the object and render a well-formed presentation of object architecture.

like image 449
Amarjit Singh Avatar asked May 27 '18 15:05

Amarjit Singh


2 Answers

You are looking for __dict__ property or dir()

print(object.__dict__)

Use pprint for beautified output

from pprint import pprint
pprint(dir(object))
like image 144
Sardorbek Imomaliev Avatar answered Nov 15 '22 12:11

Sardorbek Imomaliev


Raise an exception. Assuming you've got debug on you'll see the exception message. It's crude but it's helped me in the past.

Just:

 raise Exception("I want to know the value of this: " + myvariable_as_a_string)

Other answers & commenters ignored the crucial "and die" part of the dd() function, which prevents things like subsequent redirects.

like image 3
richplane Avatar answered Nov 15 '22 13:11

richplane