Django:如何从管理界面调用管理自定义命令执行?

时间:2012-09-03 11:10:23

标签: python django command admin

参考executing management commands from code

他们是从django管理界面调用此命令执行代码的方法吗?

我有一个自定义命令来定期更新已经scheduled as cron的数据库。 cron工作正常。我需要在需要时从管理界面手动更新数据库。

1 个答案:

答案 0 :(得分:10)

更新:只需从python代码中的任何位置调用函数call_command('compilemessages')即可运行任何管理命令。

示例:

from django.core.management import call_command
call_command('compilemessages')

如果任务绑定到admin中当前查看的对象,那么一个好方法可能是在单击按钮时实现ajax脚本调用的额外视图。可以选择将额外视图包装为芹菜任务,例如

<强> 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();
               }
           }
       });
   });
});

如果您尝试启动未绑定任务,则可以覆盖模板元素或添加一些HTML。