[英]Context Variable will not show up in Django template
我正在編寫一個博客應用程序,並且在呈現頁面時不會顯示變量。 這是我的博客應用程序的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 %}
模板加載並發送了電子郵件,但只顯示:
“后測”成功發送到。
我需要說收件人的電子郵件。
您需要在模板上下文中包括清除的數據。 但是,僅在表單有效時定義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}}
cd
僅在您的視圖內使用,但不是上下文變量。
要使其成為上下文變量並在模板中可訪問,您必須將其添加到現有的上下文變量中:
return render(request, 'blog/post/share.html', {'post': post,
'form': form,
'sent': sent,
'cd': cd})
您需要添加to
或者cd
到您的上下文:
return render(request, 'blog/post/share.html', {'post': post,
'form': form,
'sent': sent})
例如:
{'cd': cd,
'post': post,
'form': form,
'sent': sent}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.