Django returning to Valueerror

Asked

Viewed 40 times

1

I am creating a project to send emails, but I am doing some tests and I came across the following problem:

The view send_mail.core.views.index didn’t Return an Httpresponse Object. It returned None Instead.

Just below follow my lines of code:

#views
from django.shortcuts import render, render_to_response
from django.template.context import RequestContext
from .forms import SendMail


def index(request):
    if request.method == "POST":
        form = SendMail(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            print(form)
            return render_to_response('index.html', 
                context_instance=RequestContext(request, {"form": form},))
    else:
        print("ops!!")


#forms
from django import forms


class SendMail(forms.ModelForm):
    subject = forms.CharField(max_length=80)


#template
<!DOCTYPE html>
<html>
<head>
    <title>some title</title>
</head>
<body>
    <form action="." method="POST">
      {% csrf_token %}
      {{form.as_p}}
    </form>
</body>
</html>

I don’t need to save the data in a database, so I’m not using a model, I just need that, what I write inside the field textarea be printed. In the future I want to send emails with the same, the intention is to create an email Sender, where will contain a field with the customer’s email and a textarea with the desired subject.

Can anyone tell me why of the above mistake?

1 answer

1


You treated the form when the method is POST and if it is GET? just an "oops"? Try to leave your view according to the code below, making the necessary adjustments.

from django.shortcuts import render
def index(request):

    if request.method == 'POST':
        form = SendMail(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            print (cd)
            form = SendMail()   # Limpando o form
        else:
            print ('Valores inválidos')
            print (form.errors)

    else:
        form = SendMail() # Inicicializando o form

    return render(request, 'caminho/sua_template.html', {'form': form})
  • Perfect my dear, it worked perfectly, I’m grateful for your help. another problem is that Forms.Modelform asks by default for a model, so I changed it to Forms.Form.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.