简体   繁体   English

如何在django admin中添加自定义按钮以运行django管理命令

[英]How can I add custom button in django admin to run django management command

I have to add an Update button in one of the model at my django-admin page and match_action is an update button on django-admin and match_status is my management command, here is my code , actually I want , when I click update button I want to run a service named as goalserveService using management command 我必须在django-admin页面上的模型之一中添加一个Update按钮,并且match_action是django-admin上的update按钮,而match_status是我的管理命令,这是我的代码,实际上我想要的是,当我单击update按钮时要使用管理命令运行名为goeserveService的服务

admin.py` admin.py`

@admin.register(Match)
class MatchAdmin(admin.ModelAdmin):
    list_display = ['id', 'start_time', "home_club", 'away_club', 'created_on', 'status', 'lookup_id', 'timer', 'match_actions']
    search_fields = ['id', 'home_club__name', 'away_club__name']
    list_filter = ['status', 'season', 'start_time']
    inlines = [ MatchLookupInline, MatchEventInline, ]

    def lookup_id(self, obj):
        if obj.matchlookup_set.all().exists():
            return obj.matchlookup_set.get().source_match_id
        else:
            return None
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
        url(
            r'^(?P<match_id>.+)/update/$',
            self.admin_site.admin_view(self.match_update),
            name='match-update',
        ),

        ]
        return custom_urls + urls

    def match_actions(self, obj):
        print (obj.id)
        return format_html(
            '<a class="button" href="{}">Update</a>',
            reverse('admin:match-update', args=(obj.id,)),

        )

    def match_update(self, request, match_id, *args):
        from django.core.management import call_command
        call_command("match_status", match_id)

core/management/commands/match_status.py 核心/管理/命令/match_status.py

from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from core.models import UserTeam
from ourapp.models import Match


class Command(BaseCommand):
    help = 'Update  Match Status'

    def add_arguments(self, parser):
        parser.add_argument('match_id', nargs='+', type=int)

    def handle(self, *args, **options):
        # NOT_STARTED = 0
        # HF = 1
        # FT = 2
        # IN_PLAY = 3
        # FINISH = 4
        match = Match.objects.filter(id=options.get('match_id'))
        self.stdout.write(self.style.NOTICE("Match competition Name %s Match Found" % match.competition.name))
        current_time = timezone.now()


        try:
            import time

            self.stdout.write(self.style.NOTICE("Match competition Name %s Match Found" % match.competition.name if match.competition else "N/A"))

            match = Match.objects.filter(id=options.get('match_id'))
            time.sleep(5)
            from ourapp.services import goalserveService
            try:                        
                 goalserveService.run_match_events(match.pk, 2, update_df=False, update_round=False)
                 time.sleep(5)
            except:
                pass

            from django.core.management import call_command
            call_command("update_dfc_rank", 1)
        except Match.DoesNotExist:
            raise CommandError('League "%s" does not exist' % match)
        self.stdout.write(self.style.SUCCESS('Successfully closed league "%s"' % match))

but it shows an error 但显示错误

my admin page 我的管理页面

when I click update button 当我单击更新按钮时

Anytime you see .objects.filter in your code, you are returning a QuerySet . .objects.filter您在代码中看到.objects.filter时,都在返回QuerySet QuerySet s can be interpreted as a "list". QuerySet可以解释为“列表”。 For starters, replace .filter with .get to resolve the current error (but I cannot guarantee you won't run into a new error afterwards). 对于初学者,将.filter替换为.get可解决当前错误(但我不能保证以后不会遇到新错误)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM