发送帖子请求后删除数据表格

时间:2019-07-02 07:04:00

标签: django django-forms

我正在编码用户管理页面。在页面中,我有一个表单,用于添加带有发帖请求的新用户,以及带有确认表单的删除按钮。我成功添加了新用户,页面被重新加载,然后删除了任何帐户,但是以创建新用户的请求发送的表单中的数据又以新用户ID发送。如何解决?

user_management.html

{% extends 'pages/base.html' %}
{% block title %} Quản lý người dùng{% endblock %}
{% block active %}
{% endblock %}
{% block link %}
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
          integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
            crossorigin="anonymous"></script>
{% endblock %}
{% load static %}
{% block css %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/user_management.css' %}">
    <style>
        #messages {
            width: 200px;
            height: 50px;
            text-align: center;
        }
    </style>
{% endblock %}
{% block content %}
    <div class="container">
        <div class="table-wrapper">
            <div class="table-title">
                <div class="row">
                    <div class="col-sm-5">
                        <h2>Quản lý người dùng</h2>
                    </div>
                    <div class="col-sm-7">
                        <button type="button" class="btn btn-primary" data-toggle="modal"
                                data-target="#modalRegisterForm">
                            <i class="material-icons">&#xE147;</i>
                            <span>Thêm mới</span></button>
                    </div>
                </div>
            </div>
            {% ifequal msg null %}
            {% else %}
                <div id="messages" class="alert alert-success" role="alert">
                    <span class="">{{ msg }}</span>
                </div>
            {% endifequal %}
            <p id="delete-notifa"></p>
            <table class="table table-striped table-hover">
                <thead>
                <tr>
                    <th>User ID</th>
                    <th>Name</th>
                    <th>Date Created</th>
                    <th>Action</th>
                </tr>
                </thead>
                <tbody>

                {% for user in users %}
                    <tr>
                        <td>{{ user.id }}</td>
                        <td> {{ user.first_name }} {{ user.last_name }}</td>
                        <td>{{ user.date_joined }}</td>
                        <td>
                            <a href="{% url 'profile' user.id %}" class="edit" title="Edit" data-toggle="tooltip"><i
                                    class="material-icons">&#xE8B8;</i></a>
                            <a href="#comfirmationForm" class="delete" title="Delete" data-toggle="modal"
                               data-id="{{ user.id }}"><i
                                    class="material-icons">&#xE5C9;</i></a>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
            <div class="clearfix">
                <div class="hint-text">Showing <b>5</b> out of <b>25</b> entries</div>
                <ul class="pagination">
                    <li class="page-item disabled"><a href="#">Previous</a></li>
                    <li class="page-item"><a href="#" class="page-link">1</a></li>
                    <li class="page-item"><a href="#" class="page-link">2</a></li>
                    <li class="page-item active"><a href="#" class="page-link">3</a></li>
                    <li class="page-item"><a href="#" class="page-link">4</a></li>
                    <li class="page-item"><a href="#" class="page-link">5</a></li>
                    <li class="page-item"><a href="#" class="page-link">Next</a></li>
                </ul>
            </div>
        </div>
    </div>

    <div class="modal fade mt-5" id="modalRegisterForm" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header text-xs-center">
                    <h5 class="modal-title font-weight-bold" id="myModalLabel">Thêm người dùng</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body mx-3">
                    <form action="{% url 'user_management' %}" method="post" id="addNewUser">
                        {% csrf_token %}
                        <div class="form-group">
                            <div class="row">
                                <div class="col-xs-6">
                                    <input type="text" class="form-control" name="first_name" id="first_name"
                                           placeholder="First Name">
                                </div>
                                <div class="col-xs-6">
                                    <input type="text" class="form-control" name="last_name" id="last_name"
                                           placeholder="Last Name">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <input type="email" class="form-control" name="email" placeholder="Email" id="email"
                                   required="required">
                        </div>
                        <div class="form-group">
                            <input type="password" class="form-control" name="password" placeholder="Password"
                                   id="id_password"
                                   required="required">
                        </div>
                        <div class="form-group">
                            <input type="password" class="form-control" name="confirm_password" id="id_comfirm_pass"
                                   placeholder="Confirm Password" required="required"
                                   onkeyup="matchingPassword('id_password', 'id_comfirm_pass', 'msg');">
                        </div>
                        <p id="msg"></p>
                        <div class="form-group">
                            <button type="submit" class="btn btn-success btn-lg btn-block" name="add">Thêm</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div id="comfirmationForm" class="modal fade">
        <div class="modal-dialog modal-confirm">
            <div class="modal-content">
                <div class="modal-header">
                    <div class="icon-box">
                        <i class="material-icons">&#xE5CD;</i>
                    </div>
                    <h4 class="modal-title">Xác nhận</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                </div>
                <div class="modal-body">
                    <p>Do you really want to delete this user?</p>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-danger" id="btn_button">Delete</button>
                    <button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

{% endblock %}
{% block script %}
    <script>
        function matchingPassword(id_pass, id_comfirm_pass, id_msg) {
            var pass = document.getElementById(id_pass).value;
            var comfirm_pass = document.getElementById(id_comfirm_pass).value;

            if (pass != comfirm_pass) {
                document.getElementById(id_msg).style.color = 'red';
                document.getElementById(id_msg).innerHTML = "Mật khẩu không trùng nhau";
            } else {
                document.getElementById(id_msg).innerHTML = "";
            }
        }
    </script>
    <script>
        var tmp;
        $('.delete').click(function () {
            tmp = $(this).attr('data-id');
        });
        $('#btn_button').click(function () {
            $.ajax({
                url: '/delete_user',
                type: 'get',
                dataType: 'json',
                data: {
                    user_id: tmp,
                },
                success: function (data) {
                    if (data.is_error) {
                        alert("Xóa không thành công");
                        window.location.reload();
                    } else {
                        alert("Xóa thành công");
                        location.reload();
                    }
                }
            })
        })
        setTimeout(function () {
            $('#messages').hide()
        }, 1000);

        setTimeout(function () {
            $('#delete-notifa').hide()
        }, 1000);
    </script>
{% endblock %}

views.py

def user_management(request):
    if request.method == "POST":
        if 'add' in request.POST:
            first_name = request.POST.get('first_name')
            last_name = request.POST.get('last_name')
            username = request.POST.get('email')
            password = request.POST.get('password')

            user = User.objects.create_user(username=username, email=username, password=password, first_name=first_name,
                                            last_name=last_name)
            user.save()
            user_info = UserInfor(user=user)
            user_info.save()

            user_list = User.objects.all()
            msg = "Thêm thành công"
            return render(request, 'pages/user_management.html', {'users': user_list, 'msg': msg})
        else:
            user_list = User.objects.all()
            msg = "Thất bại"
            return render(request, 'pages/user_management.html', {'users': user_list, 'msg': msg})
    else:
        user_list = User.objects.all()
        return render(request, 'pages/user_management.html', {'users': user_list})


def delete_user(request):
    data = {}
    user_id = request.GET.get('user_id')
    user = User.objects.get(id=user_id)
    user_info = UserInfor.objects.get(user_id=user.id)
    user.delete()
    user_info.delete()
    data['is_error'] = User.objects.filter(id=user_id).exists()
    return JsonResponse(data)

1 个答案:

答案 0 :(得分:0)

我相信您的问题是您正在使用

type="submit" id="btn_button"$('#btn_button').click(...

我相信您的modal-footer会触发您的form标记,这就是为什么当您单击Delete按钮时会重新加载页面的原因。

同时$('#btn_button').click(function () {...通过向服务器发送GET请求来完成任务。

因此,一旦您按下delete按钮,就会发送POST通过form提交创建用户的请求,并且还会发送GET删除用户的请求。

尝试更改此内容:

<button type="button" class="btn btn-danger" id="btn_button">Delete</button>

<button type="submit" class="btn btn-danger" id="btn_button">Delete</button>

快乐编码:)