将html表单发送到Django项目中的电子邮件地址的最佳方式?

时间:2018-06-11 23:48:29

标签: javascript python html django forms

我在几乎所有网站上都看到了联系表单,它们看起来很简单。阅读如何做到这一点似乎很复杂,特别是因为大多数解决方案都使用php和服务器。我真的不懂php,而且我的项目中已经有四种语言,而且它变得势不可挡。我想要简单的东西;填写详细信息,发送电子邮件,然后完成。

填写姓名:John Doe
填写dob:6/11/2018
[提交](发送至example@example.com)

1 个答案:

答案 0 :(得分:1)

以下是如何实现这一目标的基本概述。

使用包含详细信息的表单:

from django import forms
class ContactForm(forms.Form):
    name = ...
    birht_date = ...

在视图中使用此表单,可能使用FormView

from django.conf import settings
from django.core.mail import send_mail
from django.views.generic.edit import FormView

class ContactView(FormView):
    form_class = ContactForm
    success_url = '/thanks/'

    def form_valid(self, form):
        # here you send the email
        send_email(
            sub='New contact: {}'.format(form.cleaned_data['name']),
            msg='This new contact was born  {}'.format(form.cleaned_data['birth_date']),
            from=settings.SERVER_EMAIL,
            to='example@example.com')

        return super().form_valid(form)

也许这会让你找到解决问题的正确方法。

相关问题