上下文变量不会出现在Django模板中

时间:2016-02-08 21:33:33

标签: python django django-templates

我正在编写一个博客应用程序,并且在呈现页面时不会显示变量。以下是我的博客应用的views.py功能:

def post_share(request, post_id):
    # retrieves post by id
    post = get_object_or_404(Post, id=post_id, status='published')
    sent = False

    if request.method == 'POST':
        # FORM was submitted
        form = EmailPostForm(request.POST)
        if form.is_valid():
            # form fields passed validation
            cd = form.cleaned_data

            post_url = request.build_absolute_uri(post.get_absolute_url())                                          
            subject = '{} ({}) recommends you reading "{}"'.format(cd['name'], cd['email'], post.title)
            message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments'])

            send_mail(subject, message, 'admin@myblog.com', [cd['to']])
            sent = True

    else:
        form = EmailPostForm()
    return render(request, 'blog/post/share.html', {'post': post,
                                                'form': form,
                                                'sent': sent})

forms.py

from django import forms
from .models import Comment

class EmailPostForm(forms.Form):
    name = forms.CharField(max_length=25)
    email = forms.EmailField()
    to = forms.EmailField()
    comments = forms.CharField(required=False, widget=forms.Textarea)

我的HTML模板的相关部分:

{% block content %}
    {% if sent %}
        <h1> Email successfully sent </h1>
        <p>
            "{{ post.title }}" was successfully sent to {{ cd.to }} .
        </p>
    {% else %}
        <h1> Share "{{ post.title }}" by email</h1>
        <form action="." method="post">
            {{ form.as_p }}
            {% csrf_token %}
            <input type="submit" value="Send e-mail">
        </form>
    {% endif %}

加载模板并发送电子邮件,但它只说:

  

“后测试”成功发送到。

我需要它说收件人发电子邮件。

3 个答案:

答案 0 :(得分:1)

您需要在模板上下文中包含已清理的数据。但是,cd仅在表单有效时定义,因此您可以执行以下操作:

data = {
    'post': post,
    'form': form,
    'sent': sent,
}

if sent:
    data['cd'] = cd
return render(request, 'blog/post/share.html', data)

由于您不需要模板中的整个cd字典,因此另一种选择是仅传递您需要的变量cd['to']

data = {
    'post': post,
    'form': form,
    'sent': sent,
}

if sent:
    data['sent_to'] = cd['to']
return render(request, 'blog/post/share.html', data)

然后在您的模板中,您将使用{{sent_to}}代替{{cd.to}}

答案 1 :(得分:0)

cd仅在您的视图中使用,但它不是上下文变量。

要使其成为上下文变量并且可以在模板中访问,您必须将其添加到现有的上下文变量中:

return render(request, 'blog/post/share.html', {'post': post,
                                            'form': form,
                                            'sent': sent,
                                            'cd': cd})

答案 2 :(得分:0)

您需要在上下文中添加tocd

return render(request, 'blog/post/share.html', {'post': post,
                                                'form': form,
                                                'sent': sent})

例如:

{'cd': cd,
 'post': post,
 'form': form,
  'sent': sent}