django - render_to_string无效

Ann*_*ska 11 django

我是新手.但是,如果没有愚蠢的问题......这是我的.为什么我的电子邮件(在正文部分)不包含该消息?

这是我的脆皮代码:

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, "annadrybulska@gmail.com" +'', ['annadrybulska@gmail.com'], headers = {'Reply-To': contact_email })
email.send()
Run Code Online (Sandbox Code Playgroud)

我真的很感激任何帮助..从早上9点开始工作,但仍然没有...

我的模板(contact_template.txt),(我收到的所有电子邮件都包含此内容,但没有消息):

Contact Name:


Email:


Content:
Run Code Online (Sandbox Code Playgroud)

和我的观点:(我不得不说这是令人生畏的...)

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, "annadrybulska@gmail.com" +'', ['annadrybulska@gmail.com'], headers = {'Reply-To': contact_email })
            email.send()
            return redirect('contact')

    return render(request, 'contact.html', {'form': form_class,})
Run Code Online (Sandbox Code Playgroud)

Luc*_*ops 14

为清楚起见,我会尝试将自己限制为每行的最大字符数.这使得读取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))
Run Code Online (Sandbox Code Playgroud)

您似乎缺少要在其中打印变量的模板中的位置.您定义以下变量:

  • '联系人姓名'
  • '联系电子邮件'
  • 'form_content'

但是它们不在模板中使用.例:

Contact Name:
{{ contact_name }}

Email:
{{ contact_email }}

Content:
{{ form_content }}
Run Code Online (Sandbox Code Playgroud)

  • 注意:`RemovedInDjango110Warning:不推荐使用render_to_string的context_instance参数. (4认同)