ui / django-post_office

A Django app that allows you to send email asynchronously in Django. Supports HTML email, database backed templates and logging.
MIT License
1k stars 270 forks source link

Create New Email From Django Admin #454

Open MrAlexWinkler opened 10 months ago

MrAlexWinkler commented 10 months ago

I'd really appreciate if there was a way to create a new email (not template) from the django admin. So one could send out a new newsletter at any time. Just something super simple to not have to use code.

When trying to set this up I get error that Email model is already registered in admin:


from django import forms
from django.contrib import admin
from post_office.models import Email
from post_office.admin import EmailAdmin

class CustomEmailForm(forms.ModelForm):

    class Meta:
        model = Email
        fields = '__all__'

class CustomEmailAdmin(EmailAdmin):
    form = CustomEmailForm

admin.site.unregister(Email)
admin.site.register(Email, CustomEmailAdmin)

In essence; with django post_office how to send emails manually from admin website and not with application logic?

MrAlexWinkler commented 10 months ago

I got it to work with code below. If this was added as part of the default package I think it would make a lot of sense.

urls.py

from emailapi.admin import send_email_view

urlpatterns = [
    ...
    path('send_email/', send_email_view, name='send_email'),
]

admin.py


from django.contrib import admin, messages
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django import forms

def send_email_view(request):
    if request.method == 'POST':
        form = EmailCreationForm(request.POST)
        if form.is_valid():
            email_data = form.cleaned_data
            mail.send(
                recipients=email_data['to'],
                sender=email_data['from_email'],
                subject=email_data['subject'],
                message=email_data['message'],
                html_message=email_data['html_message'],
                headers=email_data['headers'],
                priority=email_data['priority']
            )
            messages.success(request, 'Email sent successfully.')
            return redirect('admin:index')
    else:
        form = EmailCreationForm()

    return render(request, 'admin/send_email.html', {'form': form})

forms.py

from post_office.models import Email

class EmailCreationForm(forms.ModelForm):

    class Meta:
        model = Email
        fields = '__all__'  
selwin commented 9 months ago

I'd welcome a PR for this :)

MrAlexWinkler commented 9 months ago

Sounds good, I think I could get around to it before the end of the year.