我正在使用Django创建博客,我实施了这项功能,允许用户通过电子邮件分享帖子。
这里是form
from django import forms
from .models import Post
class EmailPostForm(forms.Form):
name = forms.CharField(max_length=100, required=True, widget=forms.TextInput(
attrs={'placeholder' : 'your name'}
))
email = forms.EmailField(max_length=200, required=True, widget=forms.TextInput(
attrs={'placeholder' : 'your email'}
))
to = forms.EmailField(max_length=200, required=True, widget=forms.TextInput(
attrs={'placeholder' : 'recipient\'s email'}
))
comments = forms.CharField(max_length=500, required=False, widget=forms.Textarea(
attrs={'rows' : 5, 'placeholder' : 'Tell recipient what you think about this post (optional)'}
), help_text='The maximum length of the text is 4000')
这里是view
def post_share(request, post_id):
# Retrieve the 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())
presubject = '{} ({}) recommends you reading "{}"'
subject = presubject.format(cd['name'], cd['email'], post.title)
premessage = 'Read "{}" at {}\n\n{}\'s comments: {}'
message = premessage.format(post.title, post_url, cd['name'], cd['comments'])
send_mail(subject, message, 'admin@sayc.com', [cd['to']])
sent = True
else:
form = EmailPostForm()
return render(request, 'post_share.html', {'post' : post, 'form' : form, 'sent' : sent})
这里是url
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^(?P<post_id>\d+)/share/$', views.post_share, name='post_share'),
]
这里是template
{% extends "base.html" %}
{% block title %}Share a Post - {{ block.super }}{% endblock %}
{% block content %}
<div class="mt-4 row justify-content-center">
<div class="col-lg-6 col-md-8 col-sm-10">
<div class="card">
{% if sent %}
<div class="card-body text-center">
<h3>Email Successfully Sent</h3>
<p class="lead">"{{ post.title }}" was successfully sent to {{ cd.to }}</p>
</div>
{% else %}
<div class="card-body">
<h3 class="card-title text-center">Share "{{ post.title }}" by email</h3>
<form action="." method="post" novalidate>
{% csrf_token %}
{% include 'includes/form.html' %}
<button type="submit" class="btn btn-primary btn-block">Share</button>
</form>
</div>
{% endif %}
</div>
</div>
</div>
{% endblock %}
它工作正常但每当我发送电子邮件时,模板都应该返回模板的if
块中的内容。我感到困扰的是{{ cd.to }}
(附加在模板中成功消息的末尾)并没有返回任何值。怎么了?
答案 0 :(得分:2)
您尚未将cd
传递给模板,因此无法输入该值。
<{1}}代替{{cd.to}}
,您可以使用{{form.data.to}}
来显示表单本身的值。