嘿,我在django上有一个表单,需要通过电子邮件发送结果。现在电子邮件正常工作,表格也有效。
我唯一不喜欢的是显示数据的方式我尝试使用元组和列表来发送数据。
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
standard = form.cleaned_data['standard']
atex = form.cleaned_data['ATEX']
supply_type = form.cleaned_data['supply_type']
line_frequency = form.cleaned_data['line_frequency']
supply_voltage = form.cleaned_data['supply_voltage']
power = form.cleaned_data['power']
poles = form.cleaned_data['poles']
mounting = form.cleaned_data['mounting']
efficiency = form.cleaned_data['efficiency']
protection = form.cleaned_data['protection']
frame = form.cleaned_data['frame']
brake = form.cleaned_data['brake']
force_cooling = form.cleaned_data['force_cooling']
encoder = form.cleaned_data['encoder']
form = [str(message), ('Standard',str(standard))]
if subject and message and from_email:
try:
send_mail(subject, str(form), from_email, ['jordanfeatherstone@gmail.com'], fail_silently=False)
except BadHeaderError:
return HttpResponse('Invalid header found.')
messages.success(request, 'Enquiry email successfully sent')
return render(request, 'motors.html', {'motors': motors, 'form': form})
以人类可读的方式操作结果的最佳方法是什么?
答案 0 :(得分:1)
这是一个快速演练:
如果您只是尝试发送plain text,那么事情就很容易了。
# views.py
from django.template.loader import render_to_string
# Put all the form data inside a dict, apart from the ones that will
# not be included inside the email. Just for better readiness.
context = {
standard: form.cleaned_data['standard'],
...
}
# Build the .txt file with the context data just like you build HTML templates!
plain_message = render_to_string('path/to/your/email/template.txt', context)
send_mail(subject, plain_message, from_email, ['jordanfeatherstone@gmail.com'], fail_silently=False)
如果你想要一个带有图像,样式等的HTML模板,那么事情会变得更加复杂,并且在SO中应该有一个新的问题。