获取表单值和标签,并通过电子邮件发送

时间:2012-10-04 09:05:55

标签: django django-forms

我正在尝试编写一个函数来获取表单值及其标签,以便我可以将它们放在这样的电子邮件正文中:

<p><strong>Labelvalue</strong>: formvalue</p>

这可能吗?

当我执行“body = smart_unicode(form.cleaned_data)”时,我得到了dict,但我不知道我能做些什么来获得我想要的HTML。

forms.py

class MyForm(forms.Form):
    TYPE_CHOICES = (
        (ADULT, 'Adult'),
        (CHILD, 'Child'),
    )
    type = forms.ChoiceField(widget=RadioSelect, choices=TYPE_CHOICES, label='Adult or child')
    name = forms.CharField(label='Name')
    birthdate = forms.DateField(widget=SelectDateWidget(years=range(2012,1900,-1)), label='Birthdate')
    address = forms.CharField(label='Address')
    email = forms.EmailField(label='Email')

Views.py

def show_myform(request):
    if request.method == 'POST':

        form = MyForm(request.POST)

        if form.is_valid():
            subject = "Testsubject"

            sender = form.cleaned_data['email']

            recipients = ['post@mydomain.com']

            body = smart_unicode(form.cleaned_data)

            msg = EmailMessage(subject, body, sender, recipients)
            msg.send()            
            return HttpResponseRedirect('/thanks/')


    else:
        form = MyForm()

    return render(request, 'form/myform.html', {
        'form': form,
    })

4 个答案:

答案 0 :(得分:1)

更好的方法是创建模板并使用django的render_to_string将html字符串作为正文。

您可以将form.cleaned_data传递给模板以填充模板变量。

答案 1 :(得分:1)

您可以在单独的模板中呈现电子邮件正文。如果使用Django 1.3或更高版本,请使用以下命令:

{% for field in form %}
<p><strong>{{ field.label }}</strong>: {{ field.value }}</p>
{% endfor %}

有关更多信息,请参阅Django中的BoundForm文档。

答案 2 :(得分:0)

你可以托盘将你需要的html渲染到body变量中。您还需要一个用于邮件正文的html模板:

from django.template.loader import render_to_string
body = render_to_string('yourapp/mail_template.html', {'var1':var1, 'var2':var2})

您可以将您需要的任何内容传递给模板上下文字典(例如,我使用var1和var2)。然后像这样发送邮件:

msg = EmailMessage(subject, body, sender, recipients)
msg.send()

希望这会导致正确的方向。

答案 3 :(得分:0)

是。 render_to_string成功了!

这是我更新的来源:

forms.py

class MyForm(forms.Form):
    TYPE_CHOICES = (
        (ADULT, 'Adult'),
        (CHILD, 'Child'),
    )
    type = forms.ChoiceField(widget=RadioSelect, choices=TYPE_CHOICES, label='Adult or child')
    name = forms.CharField(label='Name')
    birthdate = forms.DateField(widget=SelectDateWidget(years=range(2012,1900,-1)), label='Birthdate')
    address = forms.CharField(label='Address')
    email = forms.EmailField(label='Email')

views.py

from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.mail import send_mail, EmailMessage, EmailMultiAlternatives
from norskfamilie.forms import HealthForm
from django.utils.encoding import smart_unicode
from django.template.loader import render_to_string

def show_Myform(request):
    if request.method == 'POST':

        form = MyForm(request.POST)

        if form.is_valid():
            subject = "My subject"

            sender = form.cleaned_data['email']

            recipients = ['post@mydomain.com']

            rendered = render_to_string('email_body.html', {'form':form , 'form_headline':subject})

            msg = EmailMultiAlternatives(subject, rendered, sender, recipients)
            msg.attach_alternative(rendered, "text/html")
            msg.send()            
            return HttpResponseRedirect('/thanks/')


    else:
        form = MyForm()

    return render(request, 'form/myform.html', {
        'form': form,
    })

email_body.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
        <h1>{{ form_headline }}</h1>

        {% for field in form %}
            <p><strong>{{ field.label }}</strong>: {{ field.value }}</p>
        {% endfor %}
    </body>
</html>