简体   繁体   中英

Django DetailView + Delete Item from Ajax Form

So here is my issue.

The user can create a Client using a form. Once created, the created client appears in a DetaiLView In this DetailView, I put a form to add specific events related to the client, thanks to an ajaxified form so that new events appear without refreshing the page. So far everything is okay.

Now I would like to allow the user to delete one event if he wants to.

So I have done the HTML/AJAX parts. However, since it is a DetaiLView, I am having troubles to delete a specific event.

Here is my Views.py:

class CollectionDetail(LoginRequiredMixin, FormMixin, DetailView):
    model = Collection
    form_class = ImportantFactsForm
    template_name = 'taskflow/collection_detail.html'
    success_url = None


    def get_context_data(self, **kwargs):
        context = super(CollectionDetail, self).get_context_data(**kwargs)
        context['important_facts'] = ImportantFactsForm()
        return context


    def post(self, request, *args, **kwargs):
        form = ImportantFactsForm(request.POST)
        tgt = self.get_object()

        if form.is_valid():
            new_fact = form.save(commit=False)
            new_fact.collection_important_facts = tgt
            new_fact.save()
            return JsonResponse({'new_fact': model_to_dict(new_fact)}, status=200)
        else:
            return redirect('taskflow:collection_all')

        #here I need to implement the delete function.

Here is my collection_detail.html

<div class="card-body">
        <div class="tab-content">
          <div class="tab-pane active" id="Canal1">

              <form class="justify-content-center mx-3" id="createFactForm" method="post" data-url="{% url 'taskflow:collection_detail' pk=object.pk %}">
                {% csrf_token %}
                <div class="form-group">
                  {{important_facts.doc_ref|as_crispy_field}}
                </div>
                <div class="form-group">
                  {{important_facts.note|as_crispy_field}}
                </div>

                <button type="submit" class="btn btn-outline-success" id="createButton">Enregistrer</button>
              </form>

              {% if object.has_important_facts %}
                {% for fact in object.has_important_facts.all %}

                    <div class="card mb-1" id="factCard" data-id="{{fact.id}}" data-url="{% url 'taskflow:collection_detail' pk=object.pk %}">
                      <div class="card-body">
                        {{fact.note}}
                        <form method="post">
                          {% csrf_token %}
                          <button type="submit" formmethod="post" name="DeleteFactButton" id="DeleteButtonFact" class="btn btn-danger float-right" data-id="{{fact.id}}">Delete</button>
                        </form>

                      </div>
                    </div>


                {% endfor %}
              {% endif %}

          </div>

Here is my facts.js file

var csrfToken = $("input[name=csrfmiddlewaretoken]").val();

$(document).ready(function(){

  $("#createFactForm").on('submit', function(evt) {
    evt.preventDefault();
    var CreateFactForm = $("#createFactForm");

    $.ajax({
        url: CreateFactForm.data('url'),
        data: CreateFactForm.serialize(),
        method: 'POST',
        success: function(response) {
          console.log(response)
          $("#Canal1").append(
            '<div class="card mb-1" id="taskCard" data-id="' + response.new_fact.id + '">'+
            '  <div class="card-body">'+
                 response.new_fact.note+
            '    <button type="button" class="btn btn-danger float-right"  name="DeleteFactButton" id="DeleteButtonFact" data-id="' + response.new_fact.id + '">'+
            '    Supprimer'+
            '    </button>'+
            '  </div>'+
            '</div>');
        }

    })

    $("#createFactForm")[0].reset();
  });

  $("#DeleteButtonFact").on('click', function(response) {
    console.log(response)
    var dataID = $(this).data('id');

    $.ajax({
      url: $("#DeleteButtonFact").data('url'),
      data:{
        csrfmiddlewaretoken: csrfToken,
        id: dataID
      },
      method: 'POST',
      dataType: 'json',
      success: function() {
        $('#factCard[data-id="' + dataID + '"]').remove();
      }
    })
  });


});

Thanks for your help !

You can use deleteView, add another url path and link it to class which inherits deleteView

also for you can check the response in ajax if an error occurred and do action accordingly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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