Allow to send mail via admin interface

This commit is contained in:
Gabriel Augendre 2018-05-22 10:24:21 +02:00
parent 7709be0701
commit 2791b27729
3 changed files with 33 additions and 16 deletions

View file

@ -7,6 +7,14 @@ from manuels.models import Teacher, Book, Level, Editor, SuppliesRequirement
class TeacherAdmin(admin.ModelAdmin): class TeacherAdmin(admin.ModelAdmin):
list_display = ['full_name', 'email', 'phone_number'] list_display = ['full_name', 'email', 'phone_number']
def send_link(modeladmin, request, queryset):
for teacher in queryset:
teacher.send_link(request)
send_link.short_description = 'Envoyer le lien'
actions = [send_link]
@admin.register(Level) @admin.register(Level)
class LevelAdmin(admin.ModelAdmin): class LevelAdmin(admin.ModelAdmin):

View file

@ -1,8 +1,14 @@
import os
import re import re
import uuid as uuid import uuid as uuid
from django.conf import settings
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.core.mail import EmailMultiAlternatives
from django.db import models from django.db import models
from django.template.loader import render_to_string
from django.urls import reverse
class BaseModel(models.Model): class BaseModel(models.Model):
@ -37,6 +43,24 @@ class Teacher(BaseModel):
def __str__(self): def __str__(self):
return self.full_name return self.full_name
def send_link(self, request):
dest = self.email
link = request.build_absolute_uri(reverse('list_books', args=[str(self.pk)]))
msg = EmailMultiAlternatives(
subject='Gestion des manuels scolaires',
body=f'Bonjour {self.first_name},\n'
f'Voici votre lien pour la gestion des manuels scolaires : {link}',
from_email=settings.SERVER_EMAIL,
to=[dest],
)
reply_to = [os.getenv('REPLY_TO')]
if reply_to:
msg.reply_to = reply_to
msg.attach_alternative(
render_to_string('manuels/email.html', {'link': link, 'teacher': self}), "text/html"
)
msg.send()
class Level(BaseModel): class Level(BaseModel):
class Meta: class Meta:

View file

@ -26,22 +26,7 @@ class HomePageView(CreateView):
def form_valid(self, form): def form_valid(self, form):
response = super().form_valid(form) response = super().form_valid(form)
dest = form.cleaned_data['email'] self.object.send_link(self.request)
link = self.request.build_absolute_uri(reverse('list_books', args=[str(self.object.pk)]))
msg = EmailMultiAlternatives(
subject='Gestion des manuels scolaires',
body=f'Bonjour {self.object.first_name},\n'
f'Voici votre lien pour la gestion des manuels scolaires : {link}',
from_email=settings.SERVER_EMAIL,
to=[dest],
)
reply_to = [os.getenv('REPLY_TO')]
if reply_to:
msg.reply_to = reply_to
msg.attach_alternative(
render_to_string('manuels/email.html', {'link': link, 'teacher': self.object}), "text/html"
)
msg.send()
return response return response