简体   繁体   English

上下文变量将不会显示在Django模板中

[英]Context Variable will not show up in Django template

I am writing a blog application, and a variable will not show up when the page is rendered. 我正在编写一个博客应用程序,并且在呈现页面时不会显示变量。 Here is my views.py function for my blog app: 这是我的博客应用程序的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})

And forms.py : 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)

Relevant part of my HTML template: 我的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 %}

The template loads and the email is sent but it only says: 模板加载并发送了电子邮件,但只显示:

"Post Test" was succesfully sent to . “后测”成功发送到。

I need it to say the recipients email. 我需要说收件人的电子邮件。

You need to include the cleaned data in the template context. 您需要在模板上下文中包括清除的数据。 However, cd is only defined when the form is valid, so you can do something like: 但是,仅在表单有效时定义cd ,因此您可以执行以下操作:

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

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

Since you don't need the entire cd dictionary in the template, another option would be to pass only the variable you need, cd['to'] . 由于您不需要模板中的整个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)

Then in your template, you would use {{ sent_to }} instead of {{ cd.to }} 然后,在模板中,您将使用{{sent_to}}而不是{{cd.to}}

cd is only used within your view, but it is not a context variable. cd仅在您的视图内使用,但不是上下文变量。

To make it a context variable and accessible in the template you have to add it to your existing context variables: 要使其成为上下文变量并在模板中可访问,您必须将其添加到现有的上下文变量中:

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

You need to add to or cd to your context: 您需要添加to或者cd到您的上下文:

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

For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM