我正在開發一個物業管理應用程式,用戶可以在其中填寫一個物業的在線申請。我想設定它,以便當有人填寫申請表時,表單會通過電子郵件發送給管理員,并使用表單標簽進行格式化。有沒有辦法通過電子郵件發送帶有標簽的整個格式化表單,或者我是否必須制作電子郵件模板并根據我想要的外觀對其進行標記?
我的示例代碼:
class ApplicationView(CreateView):
redirect_field_name = ''
form_class = ApplicantForm
model = Applicant
template_name = 'base/application.html'
def form_valid(self, form):
form.instance.created_by = self.request.user
subject = 'New Application - {} {}'.format(
form.cleaned_data.get('first_name'),
form.cleaned_data.get('last_name'),
)
message = '{} {}'.format(
form.cleaned_data.get('first_name'),
form.cleaned_data.get('last_name'),
)
Application_Alert(subject, message)
return super().form_valid(form)
uj5u.com熱心網友回復:
對于電子郵件,您有兩種選擇:基于文本的電子郵件和基于 HTML 的電子郵件。所以,如果你想要一封帶有標簽和更好看的格式的電子郵件,你必須選擇基于 HTML 的選項。正如這里提到的。
最快的方法是創建一個templates/generic/_email.html并像在 ListView 中一樣繞過背景關系變數來呈現它。
uj5u.com熱心網友回復:
我們需要2個步驟:
- 在您的 中
settings.py,添加您的電子郵件資訊:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'mail.example.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = '******'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
- 在您的 中
views.py,匯入您的設定:
from django.conf import settings as my_settings
from django.core.mail import EmailMultiAlternatives
def your_def():
subject = f"{request.user} send subject"
from_email = my_settings.EMAIL_HOST_USER
to_email = ['[email protected]', '[email protected]'...]
text_content = 'This is an important message.'
# Add your email template here
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, to_email)
msg.attach_alternative(html_content, "text/html")
msg.send()
您可以在此處查看檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/395932.html
標籤:姜戈 django 模型 django-views django-forms django-模板
上一篇:檢查物件是否存在時出現奇怪的錯誤
