Django: How to invoke user control command from admin interface?

Referring to the execution of control commands from the code ,

Is their way to call this command execution code from the django admin interface?

I have a user command for periodically updating a database that was scheduled as cron . Cron is working fine. I need to update the database manually from the admin interface when necessary.

+4
source share
1 answer

update: you can run any control command simply by calling the call_command('compilemessages') function from anywhere in your python code.

If the task is attached to the object currently being viewed by the administrator, a good way might be to implement an additional view called by the ajax script when the button is clicked. An additional view may not necessarily be wrapped as a celery task, for example.

models.py

 class Foo(models.Model): # fields... def my_task_init(self): return mark_safe("<img class='loading' src='/static/img/loading.gif' alt='loading' style='display:none;' /><a data-identifier='task_%i' class='task'><img src='/static/img/process.png' style='cursor:pointer;' /></a>") % self.id my_task_init.allow_tags = True my_task_init.short_description = _(u"Execute Task") 

admin.py

 class FooAdmin(admin.ModelAdmin): list_display = ['other_field', 'my_task_init'] class Media: js = ( 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js', '/static/js/admin_tasks.js', ) def get_urls(self): urls = super(FooAdmin, self).get_urls() extra_urls = patterns('', (r'^my-task/$', self.admin_site.admin_view(self.parse_view)) ) return extra_urls + urls # optionally decorated by celery def task_view(self, request): if not request.is_ajax(): raise Http404 task_id = request.GET.get('task_id') # your logic return HttpResponse('Success') 

admin_tasks.js

 $(document).ready(function (){ $('.task').click(function(){ var image = $(this).find('img'), loading = $(this).parent().find('.loading'), task_id = $(this).data('identifier').replace('task_', ''); $.ajax({ type: "GET", data: ({'task_id': task_id}), url: "/admin/app/model/my-task/", beforeSend: function() { image.hide(); loading.show(); }, statusCode: { 200: function() { loading.hide(); image.attr('src', '/static/img/success.png'); image.show(); }, 404: function() { loading.hide(); image.attr('src', '/static/img/error.png'); image.show(); }, 500: function() { loading.hide(); image.attr('src', '/static/img/error.png'); image.show(); } } }); }); }); 

If you are trying to initiate an unrelated task, you can simply override the template element or add some html.

+7
source

Source: https://habr.com/ru/post/1432057/


All Articles