简体   繁体   中英

Django: Exposing model method to admin

Example model:

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):
        ...

I'd like to be able to expose this method to the admin so that managers can login and manually call it. I'm thinking about trying property attributes but not sure if that's gonna work. Also is it possible to expose a method like this that takes arguments other than self, possibly related objects from a select or something?

You could register it as an 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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