Django用ajax删除记录只有手动刷新后才消失

问题描述 投票:0回答:1

我想使用 Ajax 和 Sweetalert2 对话框从表中删除记录。但是,当我单击删除按钮并确认删除时,该项目将从模式中删除,但在表格中仍然可见。该元素仅在手动页面刷新后消失。

我已经查看了很多问题和视频,但我认为我缺少一些基本知识来确定我的问题..

html

<tbody>
        {% if dogs %}
            {% for dog in dogs %}
                <tr>
                    <td>{{ dog.dog_name }}</td>
                    <td>{{ dog.gender }}</td>
                    <td>{{ dog.breed }}</td>
                    <td>{{ dog.size }}</td>
                    <td>{{ dog.dob }} ({{dog.age}} Jahre)</td>
                    <td>{{ dog.owner }}</td>
                    <td>{{ dog.created_at }}</td>
                    <td>{{ dog.updated_at }}</td>
                    {% if dog.status == "ACTIVE"%}
                    <td class="text-center">
                        <span class="badge text-bg-success" style="font-size:0.7em;">{{ dog.status }}</span>
                      </td>
                    {% elif service.status == "INACTIVE"%}
                      <td class="text-center">
                        <span class="badge text-bg-danger" style="font-size:0.7em;">{{ dog.status }}</span>
                      </td>
                    {% endif %}

                    {% if request.user.is_superuser == True %}
                        <td class="text-center">
                            <!--Update-->
                            <a href="{% url 'dog_record' dog.id %}" class="text-decoration-none">
                                <button  type="button" class="btn btn-warning btn-sm" data-bs-toggle="tooltip" title="Update service">
                                    <i class="bi bi-pencil-fill"></i>
                                </button>
                            </a>

                            <!-- Delete -->
                            <button type="button" class="btn btn-danger btn-sm DeleteButton" data-url="{% url 'delete_record' dog.id %}">
                                <i class="bi bi-trash"></i>
                            </button>

                            
                        </td>
                    {% endif %}
                </tr>
            {% endfor %}
        {% endif %}
    </tbody>
  </table>

  

{% endblock %}

{% block javascripts %}

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<!--Sweet Alert-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.all.min.js"></script>

<script>

    $(document).ready(function() {

        let csrftoken = '{{ csrf_token }}'

        $('.DeleteButton').click(function(){

            Swal.fire({
                title: "Are you sure?",
                text: "You won't be able to revert this!",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "Yes, delete it!"
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        type: "POST",
                        headers:{'X-CSRFToken':csrftoken},
                        url: $(this).attr('data-url'),
                        dataType: 'json',
                        success: (data) => {
                            console.log("Item deleted");
                        },
                        error: (error) => {
                            console.log(error);
                        } 
                    });

                    Swal.fire({
                        title: "Deleted!",
                        text: "Your file has been deleted.",
                        icon: "success"
                    });      
                }
            });
            
        });
    });


</script>



{% endblock javascripts  %}

views.py

def delete_record(request, id):
    obj = get_object_or_404(Dog, id=id)

    if request.method == 'POST':
        obj.delete()
        return JsonResponse({})

url.py

path('dog/delete_dog/<int:id>', views.delete_record, name='delete_record'),

我也尝试了以下功能,但它没有改变任何东西.iews.py

#views.py

def delete_record(request, id):
    obj = get_object_or_404(Dog, id=id)

    if request.method == 'POST':
        obj.delete()
        return redirect('dogs')


def dogs(request):
    dogs = Dog.objects.all()

    if request.user.is_authenticated:
        return render(request, 'dog/dogs.html', {'dogs':dogs})
    else:
        return login_user(request)

#urls.py
path('dog/dogs/', views.dogs, name='dogs'),
django ajax crud sweetalert2
1个回答
0
投票

首先您需要为您的行分配 id。

 {% for dog in dogs %}
            <tr id="dog.id">
                <td>{{ dog.dog_name }}</td>
                <td>{{ dog.gender }}</td>

ajax调用成功后即可删除该行。

           $.ajax({
                    type: "POST",
                    headers:{'X-CSRFToken':csrftoken},
                    url: $(this).attr('data-url'),
                    dataType: 'json',
                    success: (data) => {
                        document.getElementById(this.parent.id).remove()
                    },
                    error: (error) => {
                        console.log(error);
                    } 
                });

这将更新表并删除 dom 元素。

这是您完整更新的代码。-:

<tbody>
    {% if dogs %}
        {% for dog in dogs %}
            <tr id='dog.id'>
                <td>{{ dog.dog_name }}</td>
                <td>{{ dog.gender }}</td>
                <td>{{ dog.breed }}</td>
                <td>{{ dog.size }}</td>
                <td>{{ dog.dob }} ({{dog.age}} Jahre)</td>
                <td>{{ dog.owner }}</td>
                <td>{{ dog.created_at }}</td>
                <td>{{ dog.updated_at }}</td>
                {% if dog.status == "ACTIVE"%}
                <td class="text-center">
                    <span class="badge text-bg-success" style="font- 
  size:0.7em;">{{ dog.status }}</span>
                  </td>
                {% elif service.status == "INACTIVE"%}
                  <td class="text-center">
                    <span class="badge text-bg-danger" style="font- 
        size:0.7em;">{{ dog.status }}</span>
                  </td>
                {% endif %}

                {% if request.user.is_superuser == True %}
                    <td class="text-center">
                        <!--Update-->
                        <a href="{% url 'dog_record' dog.id %}" class="text-decoration-none">
                            <button  type="button" class="btn btn-warning btn-sm" data-bs-toggle="tooltip" title="Update service">
                                <i class="bi bi-pencil-fill"></i>
                            </button>
                        </a>

                        <!-- Delete -->
                        <button type="button" class="btn btn-danger btn-sm DeleteButton" data-url="{% url 'delete_record' dog.id %}">
                            <i class="bi bi-trash"></i>
                        </button>

                        
                    </td>
                {% endif %}
            </tr>
        {% endfor %}
    {% endif %}
</tbody>
  </table>



     {% endblock %}

    {% block javascripts %}

 <!-- jQuery -->
     <script src="https://code.jquery.com/jquery-3.7.1.min.js" 
        integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" 
     crossorigin="anonymous"></script>
   <!--Sweet Alert-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.all.min.js"></script>

<script>

$(document).ready(function() {

    let csrftoken = '{{ csrf_token }}'

    $('.DeleteButton').click(function(){

        Swal.fire({
            title: "Are you sure?",
            text: "You won't be able to revert this!",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Yes, delete it!"
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    type: "POST",
                    headers:{'X-CSRFToken':csrftoken},
                    url: $(this).attr('data-url'),
                    dataType: 'json',
                    success: (data) => {
                     document.getElementById(this.parent.id).remove()                        
                     },
                    error: (error) => {
                        console.log(error);
                    } 
                });

                Swal.fire({
                    title: "Deleted!",
                    text: "Your file has been deleted.",
                    icon: "success"
                });      
            }
        });
        
    });
});


</script>



{% endblock javascripts  %}
© www.soinside.com 2019 - 2024. All rights reserved.