Почему Ajax создает новый комментарий, когда я пытаюсь отредактировать существующий?

Я пытаюсь сделать Django Blog в Class Based Views. В любом случае, они оказываются очень сложными для меня. Я чувствую, что я довольно близко... Я подозреваю, что это создает новое, потому что я комбинирую DetailView и пытаюсь включить UpdateView в мою страницу. Я переопределяю POST на DetailView... и, возможно, поэтому, когда я пытаюсь выполнить обновление комментария, переопределенный Post на DetailView переопределяет это действие?

Здесь мой код....

HTML...

<!DOCTYPE html>
  <form method='POST' class="comment-form">
    {% csrf_token %}
      <div class="spacer284">
        {{ form.comment }}
      </div>
    <button class="button7" type="submit">Submit</button>
  </form>
  <div class="spacer285">
    {% include 'suggestion_comments.html' %}
  </div>
</div>

{% endblock %}

Обратите внимание, что я делаю include, чтобы легче было просматривать комментарии...

Вот шаблон include...

  {% if suggestion_comments %}
    <h2>Comments</h2>
    {% for comment in object.suggestion_comments.all %}
      <div class="spacer291">
        <p><a href="{% url 'Main:associate_directory_associate_detail' pk=comment.author.id %}">{{ comment.author }}</a> {{ comment.created_on }}</p>
        <p class="spacer290">{{ comment.comment }}</p>
          <div class="spacer289">
            <div class="upvote-comment-count">{{ comment.total_comment_upvotes }}</div>
              <div class="hide-delete">
            <button type="button" class="button6" data-href="{% url 'Suggestions:suggestion_comment_like' comment.id %}">Like</button>
            </div>
            <div class="hide-delete">
              <button type="button" class="button2" data-href="">Reply</button>
            </div>
              {% if comment.author == request.user %}
              <button type="button" class="button4" id="{{ comment.id }}" pk="{{ object.pk }}" href="{% url 'Suggestions:suggestion_comment_edit' object.pk comment.id %}">Edit</button>
              <div class="spacer159" id="hide_payment" style="display:none;">
                  <input name="comment" id="commentInput" value="{{ comment.comment }}" class="name"/>
                  <button class="button7">Submit</button>
            </div>
            <div class="hide-delete">
              {% if user.userprofile.eDirector_queue_delete_confirm == "Yes" %}
                <button type="button" class="button5" data-href="{% url 'Suggestions:suggestion_delete' comment.id %}">Delete</button>
              {% else %}
                <button type="button" class="button3" data-href="{% url 'Suggestions:suggestion_delete' comment.id %}">Delete</button>
              {% endif %}
            </div>
            {% endif %}
          </div>
        </div>
    {% endfor %}
  {% else %}
    <h2>No Comments Yet</h2>
  {% endif %}

Я пытаюсь использовать AJAX для выполнения замены...

    $(document).on('submit', '.comment-form', function(e) { 
       e.preventDefault(); 
       var $this = $(this);
       $.ajax({
           type: "POST",
           url: $this.data("href"),
           data: $this.serialize(),
           dataType: "json",
           csrfmiddlewaretoken: "{{ csrf_token }}",
           beforeSend: function(xhr) {
             xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
           },
           success: function(response){
             console.log("so far");
             $('.spacer285').html(response['form']);
             $(".comment-form")[0].reset();
             $('.spacer288').empty('spacer288');
           },
           error: function (request, status, error) {
             console.log(request.responseText);
             showAjaxFormErrors(JSON.parse(request.responseText));
           },
        });
      });

      $(document).on('click', '.button7', function(e) {
         e.preventDefault(); 
         console.log("working123");
         var $this = $(this);
         var comment = $('#commentInput').val();
         console.log(comment);

         $.ajax({
             type: "POST",
             url: $this.data("href"),
             data: { comment: comment}, 
             csrfmiddlewaretoken: "{{ csrf_token }}",
             beforeSend: function(xhr) {
               xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
             },
             success: function(data){
               console.log(data);
               $('.comment-form1').html(data); 
             },
          });
        });

Мой DetailView...

class SuggestionDetailView(LoginRequiredMixin,DetailView):
    model = Suggestion
    context_object_name = 'suggestion_detail'
    template_name = 'suggestion_detail.html'

    def get_context_data(self, **kwargs):
        context = super(SuggestionDetailView, self).get_context_data(**kwargs)
        attachments = SuggestionFiles.objects.filter(suggestion=self.object.pk).all()
        form = SuggestionCommentForm()
        suggestion_comments = SuggestionComment.objects.filter(suggestion_id=self.object.pk).order_by('-created_on').all()
        context['attachments'] = attachments
        context['form'] = form
        context['suggestion_comments'] = suggestion_comments
        return context

    def post(self, request, *args, **kwargs):
        form = SuggestionCommentForm(request.POST)

        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.author = request.user
            new_comment.suggestion = self.get_object()
            new_comment.save()
            self.object = self.get_object()
            context = self.get_context_data(object=self.object)
            html = render_to_string('suggestion_comments.html', context, request=self.request)
            return JsonResponse({'form': html})

        else:

            form_errors = form.errors.as_json()
            response = HttpResponse(form_errors, status=400)
            response['content_type'] = 'application/json'
            return response

MyCommentUpdateView...

class SuggestionCommentUpdateView(LoginRequiredMixin, UpdateView):
    model = SuggestionComment
    fields = ["comment"]

    def form_valid(self, form):
        form.instance.suggestion_id = self.kwargs["pk"] 
        return super().form_valid(form)

И мои URL...

path("a7900f81-b66a-41ea-afc2-d7735e6d4824/suggestion_detail/<uuid:pk>/suggestion_comment_edit/<int:id>",views.SuggestionCommentUpdateView.as_view(), name='suggestion_comment_edit'),
path("a7900f81-b66a-41ea-afc2-d7735e6d4824/suggestion_detail/<uuid:pk>/",views.SuggestionDetailView.as_view(), name='suggestion_detail'),

Это все почти работает.... Моя проблема в том, что когда я нажимаю на кнопку редактировать и пытаюсь отредактировать комментарий.... он работает...и обновляет базу данных...но он добавляет новый обновленный комментарий вместо того, чтобы просто редактировать существующий комментарий. Заранее спасибо за любые мысли о том, что я могу делать неправильно.

Вернуться на верх