0

我有一个捕获用户提交数据的基本表单,并通过 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,
    })
4

1 回答 1

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
于 2013-10-15T18:13:25.843 回答