我是新手。但是,如果没有愚蠢的问题……这是我的。为什么我的电子邮件(在正文部分)不包含该消息?
这是我的脆皮代码:
message = render_to_string('contact_template.txt', {'contact_name': contact_name, 'contact_email': contact_email, 'form_content': content}, context_instance=RequestContext(request))
email = EmailMessage("New contact form submission", message, "[email protected]" +'', ['[email protected]'], headers = {'Reply-To': contact_email })
email.send()
我真的很感激任何帮助..从上午9点开始工作,仍然没有任何效果。
我的模板(contact_template.txt),(我收到的所有电子邮件都包含此模板,但没有消息):
Contact Name:
Email:
Content:
和我的看法:(我不得不说这是令人生畏的...)
from polls.forms import ContactForm
from django.core.mail import EmailMessage
from django.template import Context, Template, RequestContext
from django.shortcuts import render
from django.shortcuts import redirect
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.template.loader import render_to_string, get_template
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
def contact(request):
form_class = ContactForm
# logic!
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get('contact_name', '')
contact_email = request.POST.get('contact_email', '')
content = request.POST.get('content', '')
message = render_to_string('contact_template.txt', {'contact_name': contact_name, 'contact_email': contact_email, 'form_content': content}, context_instance=RequestContext(request))
email = EmailMessage("New contact form submission", message, "[email protected]" +'', ['[email protected]'], headers = {'Reply-To': contact_email })
email.send()
return redirect('contact')
return render(request, 'contact.html', {'form': form_class,})
最佳答案
为了清楚起见,我将尝试限制每行最多字符数。这使得读取render_to_string
行非常困难,并且更难发现错误。
context = {
'contact_name': contact_name,
'contact_email': contact_email,
'form_content': content
}
message = render_to_string('contact_template.txt', context,
context_instance=RequestContext(request))
似乎您在模板中缺少要打印变量的位置。您定义以下变量:
'联系人姓名'
'联系电子邮件'
'form_content'
但是,它们未在模板中使用。例:
Contact Name:
{{ contact_name }}
Email:
{{ contact_email }}
Content:
{{ form_content }}
关于django - django-render_to_string不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36958543/