Skip to content
Advertisement

Calling a view from a management command

So I have added a command to manage.py in my django app that basically takes the results from a view and emails them out to specific users. This command will run on a cron schedule – basically this is done as an automated, emailed report.

I’ve figured out how to add in the command but I want to call the view now. The problem is that I have no HttpRequest object and whenever I read the django docs on HttpRequest, my eyes glaze over and I struggle to follow it. I’m not sure exactly how to create an HttpRequest object that will satisfy my needs nor if there’s another way to get this done. I also tried passing ‘None’ in as the request object but that didn’t lead anywhere.

Help?

Advertisement

Answer

I think your situation is as follows:

def superDuperView(request, params,...): 
   # The logic lies here which is intended to be reused.
   ......
   ......
   return HttpResponse('template.html', {somedata}) 

You would like to reuse your view’s logic in a management command. But calling a view is without request response lifecycle seems not to be possible. Thus segregation of logic and your view would help you:

def superDuberBusinessLogic(user, params,...): 
   #implement your logic here without a need of any request.
   ......
   return result

The you view would become:

def superDuperView(request, params,...): 
   # You could pass user your logic if you need.
   data = superDuberBusinessLogic(request.user, params,....)
   return HttpResponse('template.html', {data}) 

You could use your superDuberBusinessLogic in your management command.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement