电子邮件字段中插入的数据未正确广播到后端,request.is_ajax() 返回 false

问题描述 投票:0回答:1

我正在学习有关电子商务应用程序的教程。

该应用程序是用Django 4制作的,前端使用ajax。

我目前正在制作联系页面。

编译表单并提交应该会触发 jquery-confirm 弹出窗口,显示消息“非常感谢!”。

这不是通过简单的 javascript 提交表单按钮获得的 ,但是通过自定义 ajax 逻辑。

问题是,当我编译并提交表单时,表单已验证,JavaScript已加载,但电子邮件数据未正确传输(我没有得到任何结果),并且在views.py中,

request.is_ajax()
返回None。

注:

mainapp_ecommerce/views.py
中,还有另一个函数将
request
作为使用
request.is_ajax()
的输入,并且该函数工作正常。
只有与表格链接的那个无法正常工作。

这就是我填写所有表单字段并单击提交时发生的情况:

后端:

contact_form.cleaned_data {'fullname': 'John Doe', 'email': None, 'content': 'uvyibuon'}
no ajax in this request: <WSGIRequest: POST '/contact/'>
[20/Nov/2023 16:21:15] "POST /contact/ HTTP/1.1" 200 16035

前端:

Navigated to http://127.0.0.1:8000/contact/
contact/:255 readyyyy
contact/:261 before submit

这是我的文件

mainapp_ecommerce/urls.py

urlpatterns = [
...
path('contact/', contact_page, name="contact"),
]

mainapp_ecommerce/views.py

from .forms import ContactForm

def contact_page(request):

    contact_form = ContactForm(request.POST or None)

    context = {
    "title":"Contact",
    "content":"Welcome to the contact page!",
    "form": contact_form,
    "brand":"new brand name",
    }

    if contact_form.is_valid():
        print("contact_form.cleaned_data", contact_form.cleaned_data)
        
        if request.is_ajax(): # asinchronous javascript and xml
            print("Ajax request")
        
            dict_for_jsonresponse = {
                "message": "thanks!!"
            }
            return JsonResponse(dict_for_jsonresponse)

        else:
            print("no ajax in this request:", request) 

    else:
         print("form not valid")    

    return render(request, "contact/view.html", context )

mainapp_ecommerce/forms.py

class ContactForm(forms.Form):
    # eredita dalla classe form di django

    fullname = forms.CharField(
        widget=forms.TextInput(
            attrs={
                "class": "form-control", 
                "placeholder":"Your full name", 
                "id":"form_full_name"
                }
        )
    )

    email = forms.EmailField(
        widget=forms.EmailInput(
            attrs={
                "class": "form-control", 
                "placeholder":"Your email", 
                }
        )
    )
    

    content = forms.CharField(
        widget=forms.Textarea(
            attrs={
                "class": "form-control", 
                "placeholder":"Your content goes here...", 
                }
        )
    )

    def clean_email(self):
        email = self.cleaned_data.get("email")
        if not "gmail.com" in email:
            raise forms.ValidationError("Email has to be gmail.com")

mainapp_ecommerce/middlewares.py

class AjaxMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        def is_ajax(self):
            return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
        
        request.is_ajax = is_ajax.__get__(request)
        response = self.get_response(request)
        return response

设置.py

...
MIDDLEWARE = [
    'django.middleware.security.AjaxMiddleware',
...

模板/base.html

    {% load static %}
    <!doctype html>
    <html lang="en">
      <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        

        <!-- <title>Base template</title> -->
        {% include 'base/css.html' %} <!-- questo inietta il codice di una pagina nel punto in cui è messo -->

      </head>



      <body>

        {% include 'base/navbar.html' with brand_name='eCommerce' %}
        <div class='container'>
          {% block content %}
          {% endblock %}
        </div>


      {% include 'base/js.html' %}


        <script>
          $(document).ready(function(){

            console.log("readyyyy")
            // contact form habdrler
            var contactForm = $("contact-form")
            var contactFormMethod = contactForm.attr("method")
            var contactFormEndpoint = contactForm.attr("action")  /* questo lo prende da dove ho scritto action nella view dei contatti */
            
            console.log("before submit")

            contactForm.submit(function(event){
              console.log("entro submit")
              event.preventDefault()  /* quest mi serve a prevenire che lancio il submit premendo invio */
              var contactFormData = contactForm.serialize()
              console.log("serializzazione ok")
              var thisForm = $(this)
              
              $.ajax({

                method: contactFormMethod,
                url: contactFormEndpoint,
                data: contactFormData,

                success: function(data){
                  thisForm[0].reset()  /* empty the form */
                  $.alert({
                    title: "success!",
                    content: "thank you a lot!",
                    theme: "modern",
                  })              
                }, /* success chiudo */

                error: function(error){
                  console.log(error)
                  $.alert({
                    title: "oops",
                    content: "an error occurred",
                    theme: "modern",
                  })
                }, /* chiudo error */

              }) /* chiudo ajax  */


            }) /* chuso contactofrm submint */

        


          })
        </script>



        </body>
    </html>

模板/contact/view.html

  {% extends "base.html" %}

  {% block content %}


  <!doctype html>
  <html lang="en">
    <head>
      <!-- Required meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

      <!-- Bootstrap CSS -->
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

      <title>Contact</title>

    </head>

    <body>

      <div class='text-center'>
        <h1>{{title}}</h1>
        <h3>we are working</h3>
      </div>



    <div class='container'>
    <div class='row'>
      <div class='col'>      

        <div class='col-sm-6 col-12 mx-auto'>  <!-- mx auto lo manda nel mezzo -->

          <p>{{ content }}</p>

          <!-- <div class='col-sm-6 col-12'>
          <form method='POST'>
            {% csrf_token %}
            <input type='text' class='form-control' placeholder="Name" name='fullname'>
            <input type='email' class='form-control' placeholder="Email" name='email'>
            <input type='content' class='form-control' placeholder="Your content..." name='content'>
            <button type='submit' class="btn btn-primary">Submit</button>
          </form> -->

          <form class='contact-form' method='POST' action='{% url "contact" %}'>  
            <!-- questo token url mi serve per usare jquery,per essere sicuri che lo mando nel posto giusto. l'url lo prendo dalle views -->
            <!--  il selector della classe lo uso x jquery -->
            {% csrf_token %}
            {{ form.as_p }}
            <br>
            <button type='submit' class="btn btn-primary">Submit</button>
          </form>

        </div>

      </div>

    </div>
    </div>

    <br><br>


      <!-- Optional JavaScript -->
      <!-- jQuery first, then Popper.js, then Bootstrap JS -->
      <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    </body>
  </html>


  {% endblock %}
javascript jquery django ajax forms
1个回答
0
投票

您的javascript指的是

var contactForm = $("contact-form")

然而,这实际上是在寻找该类型的标签。它无法正确识别以下内容:

<form class='contact-form' method='POST' action='{% url "contact" %}'> 

为此,您需要修改选择器。假设页面上只有该类的一个元素,则可以使用以下方法(通过将类指示符添加到选择器)

var contactForm = $(".contact-form")

但理想情况下,您可以为表单指定一个名称

<form class='contact-form' name="contact-form" method='POST' action='{% url "contact" %}'> 
var contactForm = $("form[name='contact-form']")

或者一个唯一的ID

<form class='contact-form' id="contact-form" method='POST' action='{% url "contact" %}'>
var contactForm = $("#contact-form")
© www.soinside.com 2019 - 2024. All rights reserved.