VingtCinq/django-simple-mail

An admin action to clone one mailer to others

Opened this issue · 1 comments

BoPeng commented

In my application I have multiple related emails that share similar values. Since it is tedious to copy and paste values around, I have created an admin action to copy field values from a specified SimpleMail to selected records. An additional application is to create a base mailer with the default title, content, and actions, which can be used as a template for all new emails.

Here is the code to extend the default admin with the new action, Only non-empty fields from the source record are copied to empty fields of the destination records, so the action should be pretty safe. I can create a PR if this looks like a valid addition to the package.

from simple_mail.admin import SimpleMailAdmin as BaseSimpleMailAdmin
from simple_mail.models import SimpleMail
from django.contrib.admin.helpers import ActionForm
from django import forms
admin.site.unregister(SimpleMail)

class MailerNameForm(ActionForm):
	key = forms.CharField()

@admin.action(description='Copy value from mailer')
def copy_values_from(modeladmin, request, queryset):
    mailer = SimpleMail.objects.get(key=request.POST['key'])
    for obj in queryset.all():
        updated = False
        for field in ('subject', 'title', 'body', 'banner', 'button_label', 'button_link'):
            if not getattr(obj, field) and getattr(mailer, field):
                  setattr(obj, field, getattr(mailer, field))
                  updated = True
        if updated:
            obj.save()

@admin.register(SimpleMail)
class SimpleMailAdmin(BaseSimpleMailAdmin):
    action_form = MailerNameForm
    actions = [copy_values_from]
    ordering = ('key',)
BoPeng commented

A more advanced version has been implemented and can be contributed

image