Django: using model method for admin

Model Example:

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 would like to provide this method to the administrator so that managers can log in and manually call it. I'm thinking of trying property attributes, but not sure if this will work. Is it also possible to set up a method that takes arguments other than self, possibly related objects from the selected one or something?

+3
source share
1 answer

You can register it as an administrator 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)
+7
source

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


All Articles