我有一个非常基本的电子邮件应用。表单类是:
class ContactForm(forms.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)
视图功能如下所示:
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,
})
只要我在视图中指定收件人,我就没有问题。但是,我希望将消息发送到表单字段“收件人列表”中指定的地址。 当我像这样构造视图代码时:
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
或:
recipients = request.POST.get('recipient_list', '')
if cc_myself:
recipients.append(sender)
我收到错误“'unicode'对象没有属性'append'”。简而言之,它不起作用。我做错了什么?
答案 0 :(得分:0)
由于recipient_list
是EmailField
,因此它会清除unicode。但是你试图将结果视为列表。显然,构建一个列表,一切都是花花公子:
recipients = [form.cleaned_data['recipient_list']]
if cc_myself:
recipients.append(sender)
...但实际上你应该拨打recipient
字段而不是recipient list
字段,因为只能输入1。