开发者

"recipient" from form in send mail

I have a very basic email app. The forms class is:

class ContactForm(forms开发者_如何学C.Form):
    name = forms.CharField(max_length=100)
    subject = forms.CharField(max_length=100)
    sender = forms.EmailField()
    recipient_list = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)
    cc_myself = forms.BooleanField(initial=True)

The view function looks like this:

def contact_name(request, id):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid():
        name = form.cleaned_data['name']
        subject = form.cleaned_data['subject']
        message = form.cleaned_data['message']
        sender = form.cleaned_data['sender']
        cc_myself = form.cleaned_data['cc_myself']

        recipients = ['dennis@themenace.com']
        if cc_myself:
            recipients.append(sender)

        from django.core.mail import send_mail
        send_mail(subject, message, sender, recipients)
        return HttpResponseRedirect('/') # Redirect after POST
else:
    a=Entry.objects.get(pk=id)
    form = ContactForm(instance=a) # An unbound form
return render_to_response('email.html', {
    'form': form,
})

As long as I specify the recipient in the view, I have no problem. However, I want the message to be sent to the address(es) specified in the form field "recipient list". When I structure the view code like this:

recipients = form.cleaned_data['recipient_list']
            if cc_myself:
                recipients.append(sender)

            from django.core.mail import send_mail
            send_mail(subject, message, sender, recipients)
            return HttpResponseRedirect('/') # Redirect after POST

or:

recipients = request.POST.get('recipient_list', '')
                if cc_myself:
                    recipients.append(sender)

I get error "'unicode' object has no attribute 'append'". In short, it doesn't work. What am I doing wrong?


Since recipient_list is an EmailField it cleans to unicode. But you're trying to treat the result as a list. So obviously, construct a list out of it and everything's dandy:

recipients = [form.cleaned_data['recipient_list']]
if cc_myself:
    recipients.append(sender)

... but really you should call the field recipient not recipient list as only 1 can be entered.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜