简体   繁体   中英

Display 'readable' list for output of MultipleChoiceField in email subject

I'd like to display the form output of a MultipleChoiceField in an email subject and message via Django's mail module.

Currently, the subject lists data like this:

Order placed for [u'cake', u'cheesecake'] by Patrick Beeson

Here's the portion of my form accepting the input:

class OrderForm(forms.Form):
    ORDER_TYPE_CHOICES = (
        ('cake', 'Cake'),
        ('cheesecake', 'Cheesecake'),
        ('coffee catering', 'Coffee catering'),
        ('breakfast platter', 'Breakfast platter'),
        ('cookie platter', 'Cookie platter'),
        ('gourmet desserts platter', 'Gourmet desserts platter'),   
    )
        ...
    order_type = forms.MultipleChoiceField(required=False, choices=ORDER_TYPE_CHOICES, widget=forms.CheckboxSelectMultiple)

And here's my view:

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 type: %s\nOrder description: %s\nDate needed: %s" % (name, phone_number, email_address, order_type, order_description, date_needed)

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

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

The MultipleChoiceField resolves to a list of unicode objects . One possible way to make them "human readable" is to simply map that to a str:

# map applies str to the outputted list
order_type = map(str,form.cleaned_data['order_type'])
if len(order_type) > 1:
    delineated = ', a '.join(order_type[0:-1])
    # You are free to include or omit the oxford comma
    # ... unless you feel otherwise.
    order_type = 'a {0}, and a {1}'.format(delineated,order_type[-1])
else:
    order_type = 'a {0}'.format(order_type[0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM