传递给send_mail的表单数据的Get_FOO_display方法

时间:2013-10-15 14:27:58

标签: django email django-forms

我有一个基本表单,用于捕获用户提交的数据,并通过Django的邮件模块以电子邮件形式发送。

但我希望电子邮件的主题和消息包含order_type选择的人类可读版本。

如何修改我的视图以显示此内容?

这是我的表格:

from django import forms
from django.contrib.localflavor.us.forms import USPhoneNumberField

import datetime

class OrderForm(forms.Form):
    CAKE = 'CA'
    CHEESECAKE = 'CH'
    COFFEECATERING = 'CO'
    BREAKFASTPLATTER = 'BR'
    COOKIEPLATTER = 'CP'
    GOURMETDESSERTSPLATTER = 'GD'
    ORDER_TYPE_CHOICES = (
        (CAKE, 'Cake'),
        (CHEESECAKE, 'Cheesecake'),
        (COFFEECATERING, 'Coffee catering'),
        (BREAKFASTPLATTER, 'Breakfast platter'),
        (COOKIEPLATTER, 'Cookie platter'),
        (GOURMETDESSERTSPLATTER, 'Gourmet desserts platter'),
    )
    name = forms.CharField(max_length=100, required=True, help_text='100 characters max.')
    phone_number = USPhoneNumberField(required=True, help_text='This will allow us to contact you in case of questions regarding your order. Please include your area code.')
    email_address = forms.EmailField(required=True, help_text='We will e-mail you to confirm we have received your order, and submitted it to our bakers and baristas.')
    date_needed = forms.SplitDateTimeField(required=True, help_text='We can only accept online orders that are placed three days in advance.')
    order_description = forms.CharField(required=True, help_text='Please describe your order.')
    order_type = forms.ChoiceField(required=True, choices=ORDER_TYPE_CHOICES)

这是我的观点:

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from order_form.forms import OrderForm

def order(request):
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            order_description = form.cleaned_data['order_description']
            phone_number = form.cleaned_data['phone_number']
            email_address = form.cleaned_data['email_address']
            date_needed = form.cleaned_data['date_needed']
            order_type = form.cleaned_data['order_type']

            subject = "Order placed for %s by %s" % (order_type, name)

            message = "Name: %s\nPhone number: %s\nEmail address: %s\nOrder description: %s\nDate needed: %s" % (name, phone_number, email_address, order_description, date_needed)

            from django.core.mail import send_mail
            send_mail(subject, message, 'orders@sitename.com', ['anotherperson@sitename.com', email_address])
            return HttpResponseRedirect('thanks/')
    else:
        form = OrderForm()

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

1 个答案:

答案 0 :(得分:2)

我通常只为此写一个简单的方法:

def human_order_type(order_id):
    for a_tuple in OrderForm.ORDER_TYPE_CHOICES:
        if order_id in a_tuple:
            return a_tuple[1]
    return None