[Django]-Calling a view from a management command

5๐Ÿ‘

โœ…

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.

๐Ÿ‘คscriptmonster

2๐Ÿ‘

Iโ€™ll fully admit to the hacky nature of this but if it works is it stupid?

from django.test import Client

user = User.objects.filter(is_superuser=True)[0]
assert user.is_authenticated()

c = Client()
c.force_login(user)

resp = c.get( reverse('frontend:csv-view', kwargs={'company':company.name}) )
print resp.content
๐Ÿ‘คKurt

0๐Ÿ‘

If anyone is in the situation where they need a request object,
a simple solution might be to use the curl command from a cron job

This is useful for eg. to build an absolute url in an email template

eg.

30 08 10 06 * curl http://localhost/your/view/param/etc/etc/

This bypasses the need for any management command codes.

๐Ÿ‘คPowerAktar

Leave a comment