EVA/evapp/views.py

67 lines
2.1 KiB
Python

from smtplib import SMTPException
from django.views.generic.edit import CreateView
from django.urls import reverse
from django.http import HttpResponse
from django.core.mail import send_mail, BadHeaderError
from django.template.loader import get_template
from formtools.wizard.views import CookieWizardView
from django.shortcuts import render
from .models import Employee
from .forms import EmployeeForm, PersonalForm, WorkingForm
from .settings import MAILS, EVA_MAIL
def success(request):
return HttpResponse("gut gemacht!")
def send_mail_to_department(department, data):
'send a mail to the given department with the nececcary notifications'
print(f'send mail to department {department}...')
# model = form.save() # maybe we dont need to save here and get the model instance in another way?
context = {'data': 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]
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(CookieWizardView):
model = Employee
template_name = 'evapp/employee_form.html'
form_list = [PersonalForm, WorkingForm]
# form_class = EmployeeForm
def get_success_url(self):
return reverse('success')
def done(self, form_list, **kwargs):
# self.model.save()
form_data = [form.cleaned_data for form in form_list]
for dep in MAILS:
send_mail_to_department(dep, form_data)
return render(self.request, 'evapp/dataloop.txt', {
'data': form_data,
})
return super().form_valid(form)