使用Ajax和jQuery的Django表单!无法解决如何在URL中将控制从Ajax传递到Python

2024-06-07 22:25:02 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用python文件(project/controller/functions/email/发送电子邮件.py)使用jQuery处理从ajax发送电子邮件(或任何其他任务)?还是我做错了?在

我不想重定向到另一个页面,比如Django tuts teach,我只想刷新表单并显示成功消息。(我的消息和表单刷新工作正常,但在Ajax中对URL的处理不好)。在

我在这上面搜了很多遍,但是没有找到有用的东西。一些建议或例子链接将不胜感激。在

我的文件与下面类似,只是我使用jqueryvalidate,所以有点不同,但是主体相同,我的表单是在我的版本上使用bootstrap3来布局的。在

index.html

<form method="post" action="sendemail" id="sendemail">
  <input name="name" type="text" />
  <input name="email" type="email" />
  <input name="submit" type="submit" value="send" />
</form>

main.js

^{pr2}$

我尝试将我的URL重定向到目标文件,这样我就可以使用Ajax中的URL来定位文件,如下所示。在

urls.py

from django.conf.urls import include, url
from django.contrib import admin
from . import views
from .controller.functions.email import sendemail

urlpatterns = [
  url(r'^$', views.Home, name='home'),
  url(r'^sendemail', sendemail, name='sendemail'),
  url(r'^admin/', include(admin.site.urls)),
]    

我的控制台有一个500服务器错误。在

sendemail.py

from django.core.mail import send_mail

def sendemail(request):
  if (send_mail('Subject', 'Here is the message.', 'from@example.com',
['to@example.com'], fail_silently=False)):
    print(1) #Success
  else:
    print(99) #Fail

views.py

from django.shortcuts import render
from django.views.decorators.csrf import csrf_protect
from .forms import ContactForm

@csrf_protect
def Home(request):
  tpl = 'main/index.html'
  contactNotify = ""
  contactForm = request.POST


  if request.method == 'POST':
    contactForm = ContactForm(request.POST)
    if ContactForm.is_valid():
      return render(request, tpl, context)

  else:
    contactForm = ContactForm()

context = {
    'contactForm'       : contactForm
}

return render(request, tpl, context)

在php中,我使用echo返回jQuery,因此我假设print在Python中等价于返回值而不是返回。在

发送时,我在控制台中获得以下登录: POSThttp://localhost:8888/sendemail500(内部服务器错误)


Tags: 文件djangonamefrompyimporturl表单
2条回答

您可以使用HttpResponse返回对ajax请求的响应。在

import json
from django.core.mail import send_mail
from django.http import HttpResponse

def sendemail(request):
    data = {"message":"Failed"}
    if (send_mail('Subject', 'Here is the message.', 'from@example.com',
['to@example.com'], fail_silently=False)):
        data = {"message":"Success"}
    return HttpResponse(json.dumps(data), content_type="application/json")

如果您使用的是django1.7+,那么使用JsonResponse

^{pr2}$

上面的代码将返回一个json响应,您将在ajax中获得这个成功函数

https://docs.djangoproject.com/en/1.9/ref/request-response/

Django的工作方式不同

<form method="post" action="{% 'sendemail' %}" id="sendemail">

在网址.py在

^{pr2}$

在视图.py在

from .helpers import sendemail

def sendemail_view(request):
    # here sendemail()
    # and return ALWAYS HttpResponse

记住

  1. 在urlconf匹配之后,django从视图调用一个函数。这就是django的设计方式,views==来自其他框架的控制器
  2. django视图函数名应该总是小写。在

我不知道你为什么要在你的家庭视图里听POST请求。。但我认为还有更多的事情要解决,但请尝试我的建议

相关问题 更多 >

    热门问题