TransWikia.com

Почему Django возвращает None во время валидации, хотя условие присутствует?

Stack Overflow на русском Asked by user413827 on January 26, 2021

The view blog.views.post_share didn’t return an HttpResponse object. It returned None instead.

views.py

def post_share(request, post_id):

post = get_object_or_404(Post, id=post_id,status='published')
sent = False
if request.method == 'POST':
    # Форма была отправлена на сохранение.
    form = EmailPostForm(request.POST)
    if form.is_valid():
    # Все поля формы прошли валидацию.
        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 {}nn{}'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments'])
        send_mail(subject, message, '[email protected]', [cd['to']])
        sent = True
        return render(request, 'blog/post/share.html',
        {'post': post, 'form': form, 'sent': sent})

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

forms.py

from django import forms

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

share.html

{% extends "blog/base.html" %}
{% block title %}Share a post{% endblock %}
{% block content %}
    {% if sent %}
        <h1>E-mail successfully sent</h1>
        <p>"{{ post.title }}" was successfully sent to {{ form.cleaned_data.to }}.</p>
    {% else %}
        <h1>Share "{{ post.title }}" by e-mail</h1>
        <form action="." method="post">
        {{ form.as_p }}
        {% csrf_token %}
       <input type="submit" value="Send e-mail">
       </form>
    {% endif %}

{% endblock %}

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP