【问题标题】:Form request is not going through Ajax in Django. request.is_ajax() is always false表单请求不通过 Django 中的 Ajax。 request.is_ajax() 总是假的
【发布时间】:2020-07-05 17:02:40
【问题描述】:

我一直在寻找这个解决方案,但没有一个解决方案有帮助。我正在通过 Django 学习 AJAX。然而,在下面的设置中,代码永远不会进入我的 Ajax 块,并且表单请求被直接传输,因此 request.is_ajax() 始终为 False。 .请帮帮我!!!

这是我的 create_post.html

<!DOCTYPE html>
<html>
    <head>
        <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">
    </head>
    <body>
        <div class="container pt-5">
           <form method="POST" id="post-form">
              {% csrf_token %}
              <div class="form-group">
                <label>Title</label>
                <input type="text" class="form-control" id="title" placeholder="Title">
              </div>
               <div class="form-group">
                 <label>Description</label>
                 <textarea class="form-control" id="description" placeholder="Description"></textarea>
               </div>
               <button type="submit" class="btn btn-primary">Submit</button>
            </form>
            
            <div class="row mb-2 posts">
                    {% for post in posts %}
                    <div class="col-md-6">
                        <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
                            <div class="col p-4 d-flex flex-column position-static">
                                <h3 class="mb-0">{{post.title}}</h3>
                                <p class="mb-auto">{{post.description}}</p>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                    
            </div>
        </div>

    </body>

    <script src="/static/jquery-2.2.4.min.js"></script>
    <script src="/static/bootstrap.min.js"></script>    
    <script type="text/javascript">
    $.ajaxSetup({
    headers: {'X-Requested-With': 'XMLHttpRequest'}
});

    $(document).on('submit', '#post-form',function(e){
            e.preventDefault();
            var r = confirm("Are You sure we want to change status ?");
            console.log("Its here atleast!!!");
            $.ajax({
                type:'POST',
                url:'{% url "create" %}'
                data:{
                    title:$('#title').val(),
                    description:$('#description').val(),
                    csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
                    action: 'post'
                    
                },
                success:function(json){
                    document.getElementById("post-form").reset();
                    $(".posts").prepend('<div class="col-md-6">'+
                        '<div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">' +
                            '<div class="col p-4 d-flex flex-column position-static">' +
                                '<h3 class="mb-0">' + json.title + '</h3>' +
                                '<p class="mb-auto">' + json.description + '</p>' +
                            '</div>' +
                        '</div>' +
                    '</div>' 
                    )
                },
                error : function(xhr,errmsg,err) {
                $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                    " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
                console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
            }
            });
        });
    </script>
</html>

这是我的观点.py

def create_post(request):
    # posts = Post.objects.all()
    # response_data = {}
    
    print("ENTERED create_posts")
    print("is AJAX is "+str(request.is_ajax()))
 
    posts = {}
    posts['title'] = "Post1"
    posts['description']=  "Post 1 ka description"
    
    # pdb.set_trace()
    
    if request.POST.get('action') == 'post' and request.is_ajax():
        title = request.POST.get('title')
        description = request.POST.get('description')

        response_data['title'] = title
        response_data['description'] = description

        # Post.objects.create(
        #     title = title,
        #     description = description,
        #     )
        
        return JsonResponse(response_data)

    return render(request, 'homeportal_app/create_post.html', {'posts':posts})

这是我的 urls.py

from django.urls import path
from . import views

urlpatterns = [

    
    path('', views.create_post, name="create"),

]

【问题讨论】:

  • 表单提交不是 AJAX 请求。
  • 嗨,William,如何使用 Django 使表单提交 AJAX?

标签: python django ajax


【解决方案1】:

问题是$(document).on(submit.... 它应该是这样的:

$(document).on('load', function() {
    $('#post-form').on('submit', function(event){
        preventDefault(event); //so to prevent form submission as it is default
        $.ajax({
            url: ur_url,
            method: 'post', // or 'get'
            data: $('#post-form').serialize(),
            success: function(res) {
                console.log(res + "  Done!")
            }
        });
    });
});

【讨论】:

  • 谢谢马赫迪,但它仍然无法正常工作。问题是,在表单中单击提交时,它应该出现在 Ajax 块内,而这并没有发生。
  • 是的,通常不会发生,您必须进行一些编码才能使其成为可能。
  • 你还必须知道一个 ajax 请求同时也是一个 post/get 请求的事实。因此,如果它是带有帖子或获取请求代码的 ajax 请求,则必须明确区分要对请求执行的功能。完全在代码的单独部分中。
猜你喜欢
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 2021-01-05
  • 1970-01-01
  • 2017-02-18
  • 2017-07-20
相关资源
最近更新 更多