20

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.

davidism
  • 121,510
  • 29
  • 395
  • 339
Amarjit Singh
  • 2,068
  • 19
  • 52
  • Possible duplicate of [List attributes of an object](https://stackoverflow.com/questions/2675028/list-attributes-of-an-object) – Sardorbek Imomaliev May 27 '18 at 16:03
  • Possible duplicate of [Is there a built-in function to print all the current properties and values of an object?](https://stackoverflow.com/questions/192109/is-there-a-built-in-function-to-print-all-the-current-properties-and-values-of-a) – Lemayzeur May 27 '18 at 16:08

5 Answers5

7

You are looking for __dict__ property or dir()

print(object.__dict__)

Use pprint for beautified output

from pprint import pprint
pprint(dir(object))
Peter Sobhi
  • 2,542
  • 2
  • 22
  • 28
Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
3

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.

richplane
  • 537
  • 4
  • 12
3

Actually Django does not provide this specialized function. So in order to get rid of this problem, I made a custom dd() type function and use this in all Django projects. Perhaps it can help someone.

Let's assume, we have a library folder named app_libs and in that folder we have a library file named dump.py. Like app_libs > dump.py:

from django.core import serializers
from collections.abc import Iterable
from django.db.models.query import QuerySet
from django.core.exceptions import ObjectDoesNotExist


def dd(request, data=''):
    try:
        scheme      = request.scheme
        server_name = request.META['SERVER_NAME']
        server_port = request.META['SERVER_PORT']
        remote_addr = request.META['REMOTE_ADDR']
        user_agent  = request.META['HTTP_USER_AGENT']
        path        = request.path
        method      = request.method
        session     = request.session
        cookies     = request.COOKIES

        get_data = {}
        for key, value in request.GET.lists():
            get_data[key] = value

        post_data = {}
        for key, value in request.POST.lists():
            post_data[key] = value

        files = {}
        for key, value in request.FILES.lists():
            files['name'] = request.FILES[key].name
            files['content_type'] = request.FILES[key].content_type
            files['size'] = request.FILES[key].size

        dump_data = ''
        query_data = ''
        executed_query = ''
        if data:
            if isinstance(data, Iterable):
                if isinstance(data, QuerySet):
                    executed_query = data.query
                    query_data = serializers.serialize('json', data)
                else:
                    dump_data = dict(data)
            else:
                query_data = serializers.serialize('json', [data])


        msg = f'''
            <html>
                <span style="color: red;"><b>Scheme</b></span>        : <span style="color: blue;">{scheme}</span><br>
                <span style="color: red;"><b>Server Name</b></span>   : <span style="color: blue;">{server_name}</span><br>
                <span style="color: red;"><b>Server Port</b></span>   : <span style="color: blue;">{server_port}</span><br>
                <span style="color: red;"><b>Remote Address</b></span>: <span style="color: blue;">{remote_addr}</span><br>
                <span style="color: red;"><b>User Agent</b></span>    : <span style="color: blue;">{user_agent}</span><br>
                <span style="color: red;"><b>Path</b></span>          : <span style="color: blue;">{path}</span><br>
                <span style="color: red;"><b>Method</b></span>        : <span style="color: blue;">{method}</span><br>
                <span style="color: red;"><b>Session</b></span>       : <span style="color: blue;">{session}</span><br>
                <span style="color: red;"><b>Cookies</b></span>       : <span style="color: blue;">{cookies}</span><br>
                <span style="color: red;"><b>Get Data</b></span>      : <span style="color: blue;">{get_data}</span><br>
                <span style="color: red;"><b>Post Data</b></span>     : <span style="color: blue;">{post_data}</span><br>
                <span style="color: red;"><b>Files</b></span>         : <span style="color: blue;">{files}</span><br>
                <span style="color: red;"><b>Executed Query</b></span>: <span style="color: blue;"><br>{executed_query}</span><br>
                <span style="color: red;"><b>Query Data</b></span>    : <span style="color: blue;"><br>{query_data}</span><br>
                <span style="color: red;"><b>Dump Data</b></span>     : <span style="color: blue;"><br>{dump_data}</span><br>
            </html>
        '''

        return msg
    except ObjectDoesNotExist:
        return False

when you need to use this function, just call it like this in any views.py:

from django.http import HttpResponse
from django.shortcuts import render
from django.views import View

from app_libs.dump import dd
from .models import Products

class ProductView(View):
    def get(self, request):
        data = {}
        data['page_title'] = 'products'
        data['products'] = Products.objects.get_all_product()

        template = 'products/collections.html'

        dump_data = dd(request, data['products'])
        return HttpResponse(dump_data)

        # return render(request, template, data)

that's it.

1

I was looking for something similar and there is this python package django-dump-die that provides exactly this, it was inspired from laravel. https://pypi.org/project/django-dump-die/0.1.5/

Lucian Boboc
  • 480
  • 2
  • 6
0
You can set breakpoint just after variable you need to inspect.

# for example your code looks like
...other code
products = Product.objects.all()
# here you set a breakpoint
breakpoint()
...other code
Now you need to call you code in this exact location and due to breakpoint it stops.
Then you want to look up in terminal, it switched to special mode where you need to 
enter code like this one:
products.__dict__ # and hit enter. Now you'll see all properties in your variable.