为什么在我的 'Contact' 页面的 'message' 字段中添加新行时 Django returns BadHeaderError
why does Django returns BadHeaderError when adding a new line in my 'Contact' page's 'message' field
一切正常,除非我在 "Message" 字段中通过 'enter' 添加新行。如果我不在消息文本字段中添加新行,它就会通过。
我在这里错过了什么?试图解决这个问题 2 天,在 google.
上没有类似的东西
我觉得我的 views.py 配置可能有问题:
def success(request):
return render(request, 'home/success.html')
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# send email code goes here
sender_name = form.cleaned_data['name']
sender_email = form.cleaned_data['email']
sender_phone = form.cleaned_data['phone']
sender_message = form.cleaned_data['message']
subject = "Enquiry: {0}".format(sender_message[:50])
message = "New message from {0}\n phone number: {1}\n email: {2}\n\n{3}".format(sender_name, sender_phone, sender_email, sender_message)
recipients = ['john.smith@gmail.com']
sender = "{0}<{1}>".format(sender_name, sender_email)
try:
send_mail(subject, message, sender, recipients, fail_silently=False)
except BadHeaderError:
return HttpResponse('Invalid header found')
return HttpResponseRedirect('success')
else:
form = ContactForm()
return render(request, 'home/contact.html', {'form': form})
有什么想法吗?
如documentation所述,一个BadHeaderError
被提升为"protect against header injection by forbidding newlines in header values"。
由于您将 sender_message
的一部分直接复制到 subject
header 中,因此您可能也会包含换行符。简单的解决方案是先将它们剥离。
sender_message = form.cleaned_data['message']
clean_message = sender_message.replace('\n', '').replace('\r', '')
subject = "Enquiry: {0}".format(clean_message[:50])
一切正常,除非我在 "Message" 字段中通过 'enter' 添加新行。如果我不在消息文本字段中添加新行,它就会通过。
我在这里错过了什么?试图解决这个问题 2 天,在 google.
上没有类似的东西我觉得我的 views.py 配置可能有问题:
def success(request):
return render(request, 'home/success.html')
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# send email code goes here
sender_name = form.cleaned_data['name']
sender_email = form.cleaned_data['email']
sender_phone = form.cleaned_data['phone']
sender_message = form.cleaned_data['message']
subject = "Enquiry: {0}".format(sender_message[:50])
message = "New message from {0}\n phone number: {1}\n email: {2}\n\n{3}".format(sender_name, sender_phone, sender_email, sender_message)
recipients = ['john.smith@gmail.com']
sender = "{0}<{1}>".format(sender_name, sender_email)
try:
send_mail(subject, message, sender, recipients, fail_silently=False)
except BadHeaderError:
return HttpResponse('Invalid header found')
return HttpResponseRedirect('success')
else:
form = ContactForm()
return render(request, 'home/contact.html', {'form': form})
有什么想法吗?
如documentation所述,一个BadHeaderError
被提升为"protect against header injection by forbidding newlines in header values"。
由于您将 sender_message
的一部分直接复制到 subject
header 中,因此您可能也会包含换行符。简单的解决方案是先将它们剥离。
sender_message = form.cleaned_data['message']
clean_message = sender_message.replace('\n', '').replace('\r', '')
subject = "Enquiry: {0}".format(clean_message[:50])