javascript - Django 提交按钮不适用于 Ajax 请求

标签 javascript python jquery django django-views

我正在构建一个网站,用户可以在其中创建帖子并发表评论,但是,在单击 post_detail.html 模板中的提交按钮提交评论后,没有任何反应,我也看不到错误。我正在使用 jQuery 提交表单

这是我的 post_detail View :

@login_required
def post_detail(request, id):
    data = dict()
    post = get_object_or_404(Post, id=id)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(False)
            comment.post = post
            comment.name = request.user
            comment.save()
            comments = post.comments.all()
            data['form_is_valid'] = True
            data['comments'] = render_to_string('home/posts/post_detail.html', { 'comments':comments }, request=request)
        else:
            data['form_is_valid'] = False
    else: 
        form = CommentForm
        comments = post.comments.all()
    context  = {
        'form': form,
        'comments': comments,
        'post': post
    }
    data['html_data'] = render_to_string('home/posts/post_detail.html', context,request=request)
    return JsonResponse(data)

这是我的 post_detail.html 模板:

       {% load crispy_forms_tags %}
        {% load static %}
        <script src="{% static 'js/comment.js' %}"></script>
        <div class="modal-header-sm">
          <button type="button" class="close mx-2" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="card  mt-3 rounded-0 mb-3" style="max-width: 100rem !important;">
            <div class="card-body text-dark">
              <div class="d-flex">
                <img class="img-create-post rounded-circle mr-2" style="width: 50px;height: 50px;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg"
                  alt="Profile image">
                  <span class="align-text-top"><a class="mr-2 text-dark font-weight-bolder" href="#">{{ post.author.first_name }} {{ post.author.last_name }} </a><br><p class="font-weight-light text-muted">{{ post.title }}</p></span>
                    <div class="float-right text-right ml-auto">
                      <p class="text-muted small" style="font-size: 0.7rem;">{{ post.date_posted|date:"F d, Y" }}</p>
                    </div>     
              </div>
              <p class="card-text">{{ post.content }}</p>
            </div>
            <div class="card-footer" style="height: 5rem;">
              <a class="mx-1 small" data-href='{{ post.get_api_like_url }}' data-likes='{{ post.likes.count }}' href='{{ post.get_like_url }}'><i class="fas fa-thumbs-up"></i> Like</a>
              <hr class="my-1">
                <p class="text-muted small">
                  {% if post.author == request.user %}  
                  <button class="btn btn-sm text-muted show-form-delete ml-auto" data-url="{% url 'home:post-delete' post.id %}" style="font-size: small;" style="height: 0rem;">Remove</button> 
                  {% endif %}
                  <small class="float-sm-right">
                    {{ post.likes.count }} Likes, {{ post.comments.count }} Comments
                  </small>
                </p>
            </div>
            <div class="card-body">
              <div class="row">
                  <img class="img-create-post rounded-circle mr-2" style="width: 40px;height: 40px;" src="{{ request.user.image }}" alt="Profile image">


<form method="POST" data-url="{% url 'home:post-detail' post.id %}" class="post-comment-form">
        {% csrf_token %}
          <div class="row ml-1">
          {{ form | crispy }}
          <button class="btn btn-sm ml-1 small btn-rounded btn-primary" style="height: 2.3rem;" type="submit">Add</button> 
        </div>  
      </form> 
              </div>
              <hr>
          </div>
          <div id="post-linked-comments">
            <div>
              {% include 'home/posts/post_comment.html' %}
            </div>    
          </div>
          </div>

post_comment.html 模板供您引用,但这很可能不是问题:

<ul class="list-group list-group-flush">
    {% for comment in comments %}
    <li class="list-group-item">
        <div class="d-flex">
            <img class="img-create-post rounded-circle mr-1" style="width: 20px;height: 20px;" src="{{ comment.name.image }}"
              alt="Profile image">
              <span class="align-text-top font-weight-bolder">{{ comment.name.first_name }}
                <p class="text-muted small mx-2" style="font-size: 0.7rem;">{{ comment.created_on|date:"F d, Y at: f A" }}</p><br>
                <p class="font-weight-light">{{ comment.body }}</p></span> 
          </div>
    </li>
    {% empty %}
    <li class="list-group-item">
      <div class="d-flex">
              <p class="font-weight-lighter text-muted">No comments to show</p>
        </div>
    </li>
    {% endfor %}
</ul>

最后是我在 comment.js 中的 javascript 代码:

$(document).ready(function(){
    var ShowForm = function(e){
        e.stopImmediatePropagation();
        var btn = $(this);
        $.ajax({
            url: btn.attr("data-url"),
            type: 'get',
            dataType:'json',
            beforeSend: function(){
                $('#modal-post-detail').modal('show');
            },
            success: function(data){
                $('#modal-post-detail .modal-content').html(data.html_data);
            }
        });
    };

    var SaveForm =  function(e){
        e.stopImmediatePropagation();
        var form = $(this);
        $.ajax({
            url: form.attr('data-url'),
            data: form.serialize(),
            type: form.attr('method'),
            dataType: 'json',
            success: function(data){
                if(data.form_is_valid){
                    $('#post-linked-comments div').html(data.comments);
                    alert('Comment added')
                } else {
                    $('#modal-post-detail .modal-content').html(data.html_data)
                }
            }
        })
        return false;
    }

//adding a comment
$('.comment-post-btn').click(ShowForm);
$('.post-detail-clickable-details-view').click(ShowForm);
$('#modal-post-detail').on("submit",".post-comment-form",SaveForm)

});

获取 Javascript 文件没有问题,因为 post_detail 模式弹出得很好,但是单击添加按钮后没有任何反应。

感谢您提前提供的所有帮助。

编辑:按钮应该添加到表单内,但现在单击“添加”按钮后会引发 NoReverseMatchException:

新表格:

<form method="POST" data-url="{% url 'home:post-detail' post.id %}" class="post-comment-form">
        {% csrf_token %}
          <div class="row ml-1">
          {{ form | crispy }}
          <button class="btn btn-sm ml-1 small btn-rounded btn-primary" style="height: 2.3rem;" type="submit">Add</button> 
        </div>  
      </form>

url.py:

path('post/<int:id>/', views.post_detail, name='post-detail'),

错误:

django.urls.exceptions.NoReverseMatch: Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['home/post/(?P<id>[0-9]+)/$']

已解决:我自己解决了这个问题。这是我的观点。我将评论发送到了错误的 html 模板。您可以在下面看到模板的更正 View 。

@login_required
def post_detail(request, id):
    data = dict()
    post = get_object_or_404(Post, id=id)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(False)
            comment.post = post
            comment.name = request.user
            comment.save()
            comments = post.comments.all()
            data['form_is_valid'] = True
            #data['comments'] = render_to_string('home/posts/post_detail.html', { 'comments':comments }, request=request)
            #corrected code below
            data['comments'] = render_to_string('home/posts/post_comment.html', { 'comments':comments }, request=request)       else:
            data['form_is_valid'] = False
    else: 
        form = CommentForm
        comments = post.comments.all()
    context  = {
        'form': form,
        'comments': comments,
        'post': post
    }
    data['html_data'] = render_to_string('home/posts/post_detail.html', context,request=request)
    return JsonResponse(data)

最佳答案

我相信什么也没有发生,因为提交按钮没有在任何表单标签中定义。

post_detail.html 中的代码来看,button 标记位于 form 标记之外。


  <div class="row">
      <img class="img-create-post rounded-circle mr-2" style="width: 40px;height: 40px;" src="{{ request.user.image }}" alt="Profile image">
      <form method="POST" data-url="{% url 'home:post-detail' post.id %}" class="post-comment-form">
        {% csrf_token %}
        <div class="moda-body">
          {{ form | crispy }}
        </div>
      </form>
      <button class="btn btn-sm ml-1 small btn-rounded btn-primary" style="height: 2.3rem;" type="submit">Add</button> 
  </div>

按钮标签应放置在表单的结束标签之前。


  <div class="row">
      <img class="img-create-post rounded-circle mr-2" style="width: 40px;height: 40px;" src="{{ request.user.image }}" alt="Profile image">
      <form method="POST" data-url="{% url 'home:post-detail' post.id %}" class="post-comment-form">
        {% csrf_token %}
        <div class="moda-body">
          {{ form | crispy }}
        </div>
        <button class="btn btn-sm ml-1 small btn-rounded btn-primary" style="height: 2.3rem;" type="submit">Add</button> 
      </form>
  </div>

关于javascript - Django 提交按钮不适用于 Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60942241/

相关文章:

python - 从 Bat 文件调用 Python 并获取返回码

python - Numpy:通过多维数组对多维数组进行排序

javascript - 日期选择器:显示下个月/上个月的天数(如果在当前月份的结束/开始周)

javascript - 获取所有子元素的 ID 及其输入/选择数据

javascript - JavaScript 中的 setTimeout 冲突

javascript - 图像在 mouseenter 事件 JQuery 上不断闪烁

javascript - iframe 中的全屏弹出窗口(featherlight)

javascript - 连接 python 和 javascript 进行双向通信

javascript - 我们可以使用 jquery 填充 Gmail 文本字段吗?

javascript - 使用 ng-click 和 angularjs 从页面调用指令的函数