Django комментируйте, система ответа не очищает textarea и загружает скрипты - PullRequest
0 голосов
/ 12 апреля 2020

Я создаю Django систему комментариев и ответов, но у меня возникает проблема, когда я комментирую, мне нужно обновить sh страницу для функций jquery в post_comment, чтобы работать, кажется, что функции не работает без обновления страницы, также после использования модального сообщения для отправки комментария мне нужно обновить sh страницу для текстовой области, чтобы очистить ее, иначе она останется прежней.

Это мое представление post_detail:

@login_required
def post_detail(request, guid_url):
    data = dict()
    post = get_object_or_404(Post, guid_url=guid_url)
    comments = Comment.objects.filter(post=post,reply=None)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(False)
            reply_id = request.POST.get('comment_id')
            comment_qs = None
            if reply_id:
                comment_qs = Comment.objects.get(id=reply_id)
            comment.name = request.user
            comment.post = post
            comment.reply=comment_qs
            comment.save()
        else:
            data['is_valid'] = False
    else:
        form = CommentForm
    comment_count = post.comments.count()
    context = {'post':post,
                'form':form,
                'comments':comments,
                'comment_count':comment_count,
                }
    if request.is_ajax():
        data['comments'] = render_to_string('home/posts/post_comment.html',{'comments':comments,'comment_count':comment_count},request=request)
        return JsonResponse(data)
    return render(request,'home/posts/post_detail.html',context)

мой пост_деталь. html

{% extends "home/homepage/base.html" %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
  <style>
    .modal-body {
      min-height: calc(100vh - 510px);
      overflow-y: auto;
    }
    .post-border-div {
      border: 1px solid; 
      opacity: 0.5;
    }
    button, textarea {
    outline:none !important;
    box-shadow: none !important;
    -moz-box-shadow:none !important;
    -webkit-box-shadow:none !important;
    }
    button:hover {
      opacity: 0.6;
    }
  </style>
  <script src="{% static 'js/comment.js' %}"></script>
  <script src="{% static 'js/like-api.js' %}"></script>
  <link rel="stylesheet" href="{% static 'css/post/style.css' %}">
  <div class="border-left border-right">
    <h4 class=" font-weight-bolder ml-1">{{ post.title }}</h4>
    <div class="mx-0" style="margin: 0; padding: 0;">
      <div class="mt-3 rounded-0 border-top" style="max-width: 100rem !important;">
        <div class="card-body mb-1 text-dark" style="min-height: 20rem;">
          <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="small text-muted">@{{ post.author.username }}</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>
          <div class="card-post-content">
            <p class="card-text">{{ post.content }}</p>
          </div>
        </div>
      </div>
      <hr class="mx-2 px-2" style="margin: 0;">
      <div class="d-flex justify-content-center">
        <div class="mx-4">
          <button class="btn btn-md" type="button" id="post-comment-button-viewer">
            <span class="text-secondary">
                <i class="fas fa-comment"></i>
            </span>
        </button>
        </div>
        <div id="like-section" class="mx-4 inside-post-detail">
          {% include 'home/posts/likes.html' with post=post %}
        </div>
        <div class="mx-4">
          <a class="btn btn-md" href="#">
            <span class="text-secondary">
              <i class="fas fa-share-square"></i>
            </span>
          </a>
        </div>
      </div>
        <div class="d-flex justify-content-center pb-1 mx-0">
          <div class="row mx-2" id="post-comment-form-div" style="display:none;">
            <img class="img-create-post rounded-circle mx-1" style="width: 2.3rem;height: 2.3rem;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg" alt="Profile image">
            <form method="POST" action="{% url 'home:post-detail' post.guid_url %}" class="post-comment-form" style="height: 1rem;">
              {% csrf_token %}
              <div class="input-group">
                {{ form }}
                <div class="input-group-append">
                  <button class="btn btn-sm small btn-outline-primary ml-1" style="height: 2.3rem; border-radius: 20px;" type="submit">Add</button>
                </div>
              </div>     
            </form>
          </div>
        </div>
        <hr class="text-muted post-border-div" style="margin: 0;">
        <div id="post-linked-comments" class="pb-1" style="margin: 0;">
          <div>
            {% include 'home/posts/post_comment.html' %}
          </div>    
        </div>
    </div>
  </div>
  <div class="modal fade" id="modal-post" style="overflow-y: show;">
    <div class="modal-dialog">
      <div class="modal-content"></div>
    </div>
  </div>
  <style>
    #like-count {
      display: none;
    }
  </style>
{% endblock %}

мой пост_комментарий. html:

  {% for comment in comments %}
  {% with comment_uuid=comment.get_uuid %}
  {% endwith %}
  <div class="border-bottom">
    <div class="row pt-1 pl-4" style="margin-bottom: -1.5rem;">
      <div class="col-xs">
        <img class="img-create-post rounded-circle mr-1" style="width: 2.1rem;height: 2.1rem;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg" alt="Profile image">
      </div>
      <div class="col-xs" style="margin-bottom: 0;">
        <span class="text-dark font-size-smaller" href="#" style="font-weight: 500;">{{ comment.name.first_name }}</span>
        <span class="text-muted small">•</span>
        <a class="text-muted small" href="#">@{{ comment.name.username }}</a>
        <span class="text-muted small">•</span>
        <span class="text-muted small">{{ comment.get_created_on }}</span>
        <p class="font-weight-light pl-1">{{ comment.body }}</p>
      </div>
    </div>
      <div class="mx-1 my-1 d-flex justify-content-between" style="height: 1.7rem;">
        <div class="mt-1">
          <span class="text-muted small view-replies" data-id="{{ comment_uuid }}" data-text="hide replies">view replies ({{ comment.replies.count }})</span>
        </div>
        <div>
          <button class="btn btn-md small float-right text-muted button-secondary reply-btn button-hide-outline" type="button" data-toggle="modal" data-target="modal-comment-reply"><i class="fas fa-reply"></i></button>
        </div>
      </div>
      <div class="comment-replies pl-4" id="c-{{ comment_uuid }}" style="display: none;">
        {% for reply in comment.replies.all %}
        <div class="row pl-4">
          <div class="col-xs">
            <img class="img-create-post rounded-circle mr-1" style="width: 2.1rem;height: 2.1rem;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg" alt="Profile image">
          </div>
          <div class="col-xs" style="margin-bottom: 0;">
            <span class="text-dark font-size-smaller" href="#" style="font-weight: 500;">{{ comment.name.first_name }}</span>
            <span class="text-muted small">•</span>
            <a class="text-muted small" href="#">@{{ reply.name.username }}</a>
            <span class="text-muted small">•</span>
            <span class="text-muted small">{{ reply.get_created_on }}</span>
            <p class="font-weight-light pl-1">{{ reply.body }}</p>
          </div>
        </div>
        {% empty %}
        <div class="d-flex justify-content-center">
          <p class="m-0 small text-muted">No replies to show</p>
        </div>
        {% endfor %}
      </div>
  </div>
  <div class="modal fade" id="modal-comment-reply">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header" style="height:3.3rem;margin-top: -10px;">
          <p style="font-weight: bold;font-size: 1.4rem;"><span class="font-weight-light">replying to </span>@{{ comment.name.username }}</p>
          <button type="button" class="button-hide-outline" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <form method="POST" action="." class="comment-reply-form" style="height: 1rem;">
            {% csrf_token %}
            <input type="hidden" name="comment_id" value="{{ comment.id }}"/>
            <div class="comment-reply-form" style="min-height: 10rem;">
              {{ form }}
            </div>
            <div class="d-flex my-2 justify-content-between">
              <div></div>
              <div>
                <button class="btn btn-md small btn-outline-primary ml-1" style="border-radius: 20px;" type="submit">Reply</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
    {% empty %}
    <div class="d-flex justify-content-center">
      <p class="font-weight-lighter text-muted">No comments to show</p>
    </div>
{% endfor %}
<style>
  .view-replies:hover {
    cursor: pointer;
    text-decoration: underline;
  }
  .comment-reply-adjust {
    border:none !important;
    outline:none !important;
    box-shadow: none !important;
    -moz-box-shadow:none !important;
    -webkit-box-shadow:none !important;
    font-weight: 450;
    font-size: 1.3rem;
    max-height:9rem;
    overflow-y:auto;
  }
  .button-hide-outline{
    border:none !important;
    outline:none !important;
    box-shadow: none !important;
    -moz-box-shadow:none !important;
    -webkit-box-shadow:none !important;
  }
  .button-hide-outline:hover {
    opacity: 0.6;
  }
</style>
<script>
$(document).ready(function () {
  $("#modal-comment-reply textarea").attr("placeholder","Add your reply")
  $("#modal-comment-reply textarea").addClass("comment-reply-adjust")
    $('.reply-btn').on("click", function () {
    $("#modal-comment-reply").modal("show");
  });
  var l = 0;
    $('.view-replies').on('click', function () {
    var id = $(this).data('id');
    var curr_text = $(this).text();
    var new_text = $(this).data('text');
    $(this).text(new_text).data('text',curr_text);
        if(l == 0){
            $("#c-"+id).show();
            l = -1;
        } else {
            $("#c-"+id).hide();
            l = 0;
        }
    })
})
</script>

и мой комментарий. js:

$(document).ready(function(){
    $('textarea').keyup(function (e) {
        var rows = $(this).val().split("\n");
        $(this).prop('rows', rows.length);
      });
    var s = 0;
    var l = 0;
    $("#post-comment-button-viewer").click(function(){
        if(s == 0){
            $("#post-comment-form-div").fadeIn();
            s = -1;
        } else {
            $("#post-comment-form-div").fadeOut();
            s = 0;
        }
      })
    $('.inside-post-detail #likeBtn').on("click", function (e) {
        e.preventDefault();
        if($(".inside-post-detail #likeBtn i").hasClass("fa-thumbs-up")){
            ($(".inside-post-detail #likeBtn i").removeClass("fa-thumbs-up"))
            ($(".inside-post-detail #likeBtn i").addClass("fa-thumbs-down"))
        } else {
            ($(".inside-post-detail #likeBtn i").removeClass("fa-thumbs-down"))
            ($(".inside-post-detail #likeBtn i").addClass("fa-thumbs-up"))
        }
    })
    $(".post-comment-form").on("submit", function (e) {
        e.preventDefault();
        e.stopImmediatePropagation();
        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data: $(this).serialize(),
            dataType: 'json',
            success: function(data) {
                $("#post-linked-comments div").html(data.comments)
                $('textarea').val('')
                $('#modal-comment-reply').modal('hide');
                $('textarea').val('')
            },
            error: function(rs, e){
                console.log(rs.responeText);
            },
        })
    })
});

Итак, в целом я сталкиваюсь с тремя проблемами:

  1. После добавления комментария мне нужно обновить sh страницу для ответа и кнопки «Просмотреть ответы», чтобы Работа. без обновления страницы они не работают

  2. После того, как я отправляю ответ с использованием модального режима, текстовая область не отправляется и остается прежней (просто закрывается)

Заранее всем спасибо за помощь!

...