WMDE
/
eva
forked from tohe/eva
7
1
Fork 0
eva/evapp/views.py

57 lines
1.6 KiB
Python
Raw Normal View History

2021-01-06 09:59:47 +00:00
from smtplib import SMTPException
from django.views.generic.edit import CreateView
2021-01-05 13:10:28 +00:00
from django.urls import reverse
from django.http import HttpResponse
2021-01-06 09:59:47 +00:00
from django.core.mail import send_mail, BadHeaderError
from django.template.loader import get_template
from .models import Employee
from .forms import EmployeeForm
2021-01-06 09:59:47 +00:00
from .settings import MAILS, EVA_MAIL
2020-12-23 10:42:57 +00:00
2021-01-05 13:10:28 +00:00
def success(request):
return HttpResponse("gut gemacht!")
def send_mail_to_department(department, form):
'send a mail to the given department with the nececcary notifications'
2021-01-06 09:59:47 +00:00
print(f'send mail to department {department}...')
model = form.save()
context = {'data': {}}
# add all relevant fields of the form to the template context
data = MAILS[department]['DATA']
for key in data:
context['data'][key] = form.cleaned_data[key]
2021-01-06 09:59:47 +00:00
try:
mail_template = get_template(f'evapp/{department}_mail.txt')
send_mail(
'EVA: Neuzugang',
mail_template.render(context),
EVA_MAIL,
[MAILS[department]['MAIL']],
fail_silently=False)
except BadHeaderError:
# modell.delete()
return HttpResponse('Invalid header found. Data not saved!')
except SMTPException:
# modell.delete()
return HttpResponse('Error in sending mails (propably wrong adress?). Data not saved!')
class EvaFormView(CreateView):
model = Employee
form_class = EmployeeForm
2021-01-05 13:10:28 +00:00
def get_success_url(self):
return reverse('success')
def form_valid(self, form):
for dep in MAILS:
send_mail_to_department(dep, form)
2021-01-05 13:10:28 +00:00
return super().form_valid(form)