在Django 1.8中将表单输出发送到电子邮件时遇到格式问题。输出包括两个选项卡,用于以纯文本电子邮件形式发送的每个语句。如何删除标签或确保输出位于最左侧?
以下是输出示例。我每次都会在电子邮件中收到:
Business: DS2
Location:
sdad
sdasd
sadasd
Description:
sdasd
asd
asd
Host Ticket: None
System Ticket: None
Created By: user
以下是我的views.py
class NotifyCreate(CreateView):
model = Notify
template_name = "notify/add.html"
fields = [
"priority",
"business",
"location",
"description",
"host",
"system",
]
def form_valid(self, form, *args, **kwargs):
form.instance.user = self.request.user
priority = form.cleaned_data.get("priority")
business = form.cleaned_data.get("business")
location = form.cleaned_data.get("location")
description = form.cleaned_data.get("description")
host = form.cleaned_data.get("host")
system = form.cleaned_data.get("system")
subject = "%s Notification"%(priority)
message = """
Business: %s
\n
Location: %s
\n
Description: %s
\n
Host Ticket: %s
\n
System Ticket: %s
\n
Created By: %s
\n
"""%(
business,
location,
description,
host,
system,
self.request.user)
from_email = 'donotreply@_.com'
to_email = 'user@_.com'
if subject and message and from_email and to_email:
try:
send_mail(subject, message, from_email, [to_email], fail_silently=False)
except BadHeaderError:
return HttpResponse('Invalid header found.')
return super(NotifyCreate, self).form_valid(form)
else:
return HttpResponse('Make sure all fields are entered and valid.')
如果可能的话,我希望输出就像标准的明文电子邮件..
答案 0 :(得分:0)
在多行字符串中,您不应该缩进每个新行的开头,因为该字符串中包含该空格。它应该是:
def form_valid(self, form, *args, **kwargs):
...
message = """
Business: %s
\n
Location: %s
\n
Description: %s
\n
Host Ticket: %s
\n
System Ticket: %s
\n
Created By: %s
\n
"""%(
business,
location,
description,
host,
system,
self.request.user)
如果您认为看起来很难看,可以使用ddent
from textwrap import dedent
def form_valid(self, form, *args, **kwargs):
...
message = dedent("""
Business: %s
\n
Location: %s
\n
Description: %s
\n
Host Ticket: %s
\n
System Ticket: %s
\n
Created By: %s
\n
""" % (...))