Ich erstelle einen Blog mit Django und es gibt diese Funktion, die ich implementiert habe, die es Benutzern ermöglicht, Beiträge per E-Mail zu teilen.Ich kann nicht auf den Wert des `to` -Feldes zugreifen
Hier ist die 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')
Hier ist die 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, '[email protected]', [cd['to']])
sent = True
else:
form = EmailPostForm()
return render(request, 'post_share.html', {'post' : post, 'form' : form, 'sent' : sent})
Hier ist die url
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^(?P<post_id>\d+)/share/$', views.post_share, name='post_share'),
]
Und hier ist die 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 %}
Es funktioniert gut, aber jedes Mal, wenn ich eine E-Mail sende, soll die Vorlage zurückgeben, was im if
Block der Vorlage ist. Was mich nervt ist die Tatsache, dass {{ cd.to }}
(am Ende der Erfolgsmeldung in der Vorlage angefügt) keinen Wert zurückgibt. Was ist los mit dir?
Es funktioniert. Vielen Dank! – Caspian