[Django]-Laravel's dd() equivalent in django

7👍

You are looking for __dict__ property or dir()

print(object.__dict__)

Use pprint for beautified output

from pprint import pprint
pprint(dir(object))

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.

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/

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.

Leave a comment