Django:将模型方法暴露给管理员

时间:2010-09-02 00:19:54

标签: python django django-models django-admin

示例模型:

class Contestant(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    email = models.EmailField()
    ...

    def send_registration_email(self):
        ...

我希望能够将此方法公开给管理员,以便管理员可以登录并手动调用它。我正在考虑尝试属性属性,但不确定这是否会起作用。还有可能公开一个这样的方法,它接受除self之外的参数,可能是select或者某些东西的相关对象吗?

1 个答案:

答案 0 :(得分:7)

您可以将其注册为admin action

from django.contrib import admin
from myapp.models import Contestant

def send_mail(modeladmin, request, queryset):
    for obj in queryset:
        obj.send_registration_email()

make_published.short_description = "Resend activation mails for selected users"

class ContestantAdmin(admin.ModelAdmin):
    list_display = [...]
    ordering = [...]
    actions = [send_mail]

admin.site.register(Contestant, ContestantAdmin)