DEV Community

Kamal Mustafa
Kamal Mustafa

Posted on

Passing Django request object

It handy to pass the request object around but that's a bad practice. Maybe it's influenced from past experiences in PHP where $_REQUEST is available from anywhere in your code.

Limit request object in views function only. It should gather all the required data from the request, maybe using form or serializer. Calling other functions from the views function should only pass specific parameters that function need.

This will make testing easier as you don't have to mock the request object when testing specific functions that are not views. It encourage better API for your functions, for example:-

def get_articles(user, category):
    pass
Enter fullscreen mode Exit fullscreen mode

Instead of:-

def get_articles(request):
    category = request.GET.get("category")
    user = request.user
    ...
Enter fullscreen mode Exit fullscreen mode

Top comments (0)