【问题标题】:Is there a way I can solve this syntax error?有没有办法解决这个语法错误?
【发布时间】:2020-12-13 02:02:17
【问题描述】:

我的代码出现 SyntaxError: 'return' outside function。 我检查了压痕,没问题,有人可以帮我吗? 这是我的代码。

from django.shortcuts import render
from .forms import form
from django.core.mail import send_mail
from django.http import HttpResponse, HttpResponseRedirect


def index(request):
    return render(request, 'index.html', {})

if form.is_valid():
    name = form.cleaned_data['name']
    email = form.cleaned_data['name']
    message = form.cleaned_data['name']
    sender = form.cleaned_data['sender']
    cc_myself = form.cleaned_data['cc_myself']
    
    recipients = ['hillariouskelly@gmail.com']
    if cc_myself:
        recipients.append(sender)

    send_mail(name, email, message, sender, recipients)
    return HttpResponseRedirect('/thanks/')

【问题讨论】:

    标签: python python-3.x django django-forms


    【解决方案1】:

    return 从函数返回,因此return 必须在函数定义内。您在某个函数定义之外有一个return。

    错误信息会告诉你问题出现在哪一行。

    【讨论】:

      【解决方案2】:
      from django.shortcuts import render
      from .forms import form
      from django.core.mail import send_mail
      from django.http import HttpResponse, HttpResponseRedirect
      
      
      def index(request):
          return render(request, 'index.html', {})
      
      def submit(form):
          if form.is_valid():
              name = form.cleaned_data['name']
              email = form.cleaned_data['name']
              message = form.cleaned_data['name']
              sender = form.cleaned_data['sender']
              cc_myself = form.cleaned_data['cc_myself']
          
              recipients = ['hillariouskelly@gmail.com']
                  if cc_myself:
                      recipients.append(sender)
      
              send_mail(name, email, message, sender, recipients)
              return HttpResponseRedirect('/thanks/')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-28
        • 2021-06-05
        • 1970-01-01
        • 2020-02-25
        • 2020-02-18
        • 1970-01-01
        • 2021-05-07
        • 2020-09-16
        相关资源
        最近更新 更多