简体   繁体   English

Django 在引导模式中提交表单

[英]Django submit form in bootstrap modal

i know that there are a lot of posts with similar topic as this one, but none of them seem to be a useful fix in my case at least.我知道有很多与此主题相似的帖子,但至少在我的情况下,它们似乎都不是有用的解决方法。 As the headline describes i want to be able to send a new comment form to my database from a bootstrap modal.正如标题所描述的,我希望能够从引导模式向我的数据库发送一个新的评论表单。 My data is being shown just fine so the only problem i got is that when i fill out the data for a new comment and press the submit button the modal is just being dismissed and no action has happened in my DB.我的数据显示得很好,所以我遇到的唯一问题是,当我填写数据以获取新评论并按下提交按钮时,模式只是被关闭并且我的数据库中没有发生任何操作。 My best guess for why it is not working is because i got my modal data in a separated html file detail.html.我对它为什么不起作用的最佳猜测是因为我在一个单独的 html 文件 detail.html 中获得了我的模态数据。 But otherwise i was not able to display the right data for each posts.但否则我无法为每个帖子显示正确的数据。

button to open the modal in home.html:按钮打开 home.html 中的模态:

<a class="btn btn-outline-primary post_details-btn" class="open-modal" data-url="{% url 'post_detail' post.pk %}" width="17" height="17"><i class="fa fa-comments"></i></a>

my modal in home.html where i display the data from detail.html in the div with the id = modal-div我在 home.html 中的模态,我在 id = modal-div 的 div 中显示来自 detail.html 的数据

<div class="modal fade" id="myModal2">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="staticBackdropLabel">WINNER:</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"                       aria-label="Close"></button>
              </div>
              <div class="modal-body">
                <div id="modal-div"></div>
            </div>
          </div>
        </div> 
        </div>

my jquery to display the html code from detail.html in the modal, this code is also located in home.html我的 jquery 从详细信息中显示 html 代码。html 在模态中,此代码也位于模态中。

                 var modalDiv = $("#modal-div");
                $(".post_details-btn").on("click", function() {
                  $.ajax({
                     
                    url: $(this).attr("data-url"),
                    success: function(data) {
                      $('#myModal2').modal('show');
                      modalDiv.html(data);
                    }
                  });
                });

detail.html详情.html

{% block content %}
{% load static %}
 
  <div class="container">
  <div class="row">

    <div class="col-md-8 card mb-4  mt-3 ">
      <div class="card-body">
        <!-- comments -->
        <h2>{{ comments.count }} comments</h2>

        {% for comment in comments %}
        <div class="comments" style="padding: 10px;">
          <p class="font-weight-bold">
            {{ comment.name }}
            <span class=" text-muted font-weight-normal">
              {{ comment.created_on }}
            </span>
          </p>
          {{ comment.body | linebreaks }}
        </div>
        {% endfor %}
      </div>
    </div>
    <div class="col-md-8 card mb-4  mt-3 ">
      <div class="card-body">
        {% if new_comment %}
        <div class="alert alert-success" role="alert">
          Your comment is awaiting moderation
        </div>
        {% else %}
        <h3>Leave a comment</h3>
        <form method="post" style="margin-top: 1.3em;">
          {{ comment_form.as_p }}
          {% csrf_token %}
          <button type="submit" class="btn btn-primary submit">Submit</button>
        </form>
        {% endif %}
      </div>
    </div>
  </div>
 </div>





{% endblock content %}

my post_detail function in views.py我在views.py中的post_detail function

def post_detail(request, pk):
    allposts= Posts.objects.all()
    alltags = Tag.objects.all()

    post = get_object_or_404(Posts, pk=pk)
    comments = post.comments.filter(active=True)
    new_comment = None
    # Comment posted
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            # Create Comment object but don't save to database yet
            new_comment = comment_form.save(commit=False)
            # Assign the current post to the comment
            new_comment.post = post
            # Save the comment to the database
            new_comment.save()
            print("form is send!")

    else:
        comment_form = CommentForm()
    
    context = {
        'alltags': alltags,
        'allposts': allposts,
        'post': post,
        'comments': comments,
        'new_comment': new_comment,
        'comment_form': comment_form,
        'alltags': alltags,
    }
    return render(request, 'detail.html', context)

i did manage to get a solution myself after days of researching.经过几天的研究,我确实设法自己找到了解决方案。 The solution was to add the url in action attribute in the detail.html to the function in views.py that handles the comment form.解决方案是将 url 在 detail.html 的 action 属性中添加到处理评论表单的 views.py 中的 function 中。

        <form method="post" action="{% url 'post_detail' post.pk %}">
          {{ comment_form.as_p }}
          {% csrf_token %}
          <button type="submit" class="btn btn-primary">submit</button>
        </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM