【问题标题】:Passing data form datatable to modal django将数据表单数据表传递给模态django
【发布时间】:2017-12-31 18:41:23
【问题描述】:

我想将数据表中的数据显示到模态引导程序。

例子:

Name    | prenom | id |edit
example | test   |  2 |button edit 

按钮会将数据发送到模态显示以进行更新。

按钮代码:

<a class="btn btn-info" role="button" data-toggle="modal" data-form="{% url 'up' id=val.id }" data-target="#myEdit" >Edit</a>

模式代码:

<div class="modal fade" id="myEdit" role="dialog">
    <div class="modal-dialog">
        <form  class="well contact-form" method="post" action="{% url 
      'up'}">
            {% csrf_token %}
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Modal Header</h4>
                </div>
                <div class="modal-body">
                    <label for="usr">Name:</label>
                    <input type="text" class="form-control" required="" name="uss" value="{{ instance.name }}" id="uss">
                    <label for="pwd">Password:</label>
                    <input  type="password"  class="form-control" required="" value="{{ instance.sname }}" name="pwd" id="pwd" >
                </div>
                <div class="modal-footer">
                    <button  type="submit" class="btn btn-default">Valider</button>
                    <button  value="" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </form>
    </div>
</div>

views.py

def posts_edit(request, id=None):
    instance = get_object_or_404(namemodel, id=id)
    context={
        'instance': instance
    }
    return render(request, '/ges/sortie/', context)

我想在模态中显示两个值Nameprenom,数据从数据库中显示出来。

我认为最好的解决方案是使用 ajax。

【问题讨论】:

  • 我不认为我理解你想要达到的目标。您是否希望当用户单击“编辑”按钮时打开模式并显示填充数据的表单?
  • 是的兄弟,这正是我需要的hhhh

标签: python ajax django bootstrap-modal


【解决方案1】:

您的模态代码包含form,但您在询问如何显示一些数据,所以这让我有点困惑您真正想要做什么。请更清楚。

我假设您想在modal 上显示一些数据,并且应该使用 AJAX 从服务器检索这些数据。

有几种方法可以做到这一点。让我向您解释两个一般选项:

1。服务器处理的 HTML

在您的初始模板中,您只有一个空的 div,您可以使用 HTML 代码对其进行更新。

每次您想显示一些数据时,您都会执行一个 AJAX 请求这将返回 HTML 代码(在本例中为 modal HTML 代码),然后您只需将其插入您的 div

2。客户端处理的 HTML

在您的初始模板中,您可能有 HTML 代码的骨架(在本例中为 modal HTML 骨架),您可以通过 javascript 更新其中的一些值。

每次您想要显示一些数据时,您都会执行一个 AJAX 请求可能会返回 JSON 数据并使用该信息更新 HTML 框架中的值。


区别

使用第一个意味着在后端编写更多代码(在本例中为 Django 模板),而后者鼓励您在前端编写更多 javascript 代码。

由于在服务器端渲染模板非常慢并且传输的数据也更大(所有 HTML 代码通常包含比原始 JSON 数据更多的字节),前一种选项可能会慢一些。无论如何,我相信对于这种简单的情况,这种差异是无关紧要的。


代码

由于我更喜欢​​在后端工作而不是编写过多的 javascript,因此以下解决方案将是 Server Processed HTML 的实现。在这里(顺便说一句,你非常接近):

您的主要模板:

<table class="table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Prenom</th>
      <th>ID</th>
      <th>Edit</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>{{ val.name }}</td>
      <td>{{ val.prenom }}</td>
      <td>{{ val.id }}</td>
      <td><a class="btn btn-info" class="open-modal" data-url="{% url 'up' id=val.id }">Edit</a></td>
    </tr>
    <tr>
      ...
    </tr>
    ...
  </tbody>
</table>

<!-- Here we create this empty div for inserting modal -->
<div id="modal-div"></div>

主模板中的Javacript:

var modalDiv = $("#modal-div");

$(".open-modal").on("click", function() {
  $.ajax({
    url: $(this).attr("data-url"),
    success: function(data) {
      modalDiv.html(data);
      $("#myEdit").modal();
    }
  });
});

这里重要的是我们有我们的按钮和一个当有人点击它时触发的 jQuery 事件。触发函数进行AJAX调用,将返回的HTML设置为modal-div,最后打开全新的modal。

你的控制器(Django 视图):

def posts_edit(request, id=None):
    instance = get_object_or_404(namemodel, id=id)
    context={
        'instance': instance
    }
    return render(request, 'modal.html', context)

你的模态模板modal.html

<div class="modal fade" id="myEdit" role="dialog">
  <div class="modal-dialog">
    <form  class="well contact-form" method="post" action="{% url 'up'}">
      {% csrf_token %}
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <label for="usr">Name:</label>
          <input type="text" class="form-control" required="" name="uss" value="{{ instance.name }}" id="uss">
          <label for="pwd">Password:</label>
          <input  type="password"  class="form-control" required="" value="{{ instance.sname }}" name="pwd" id="pwd" >
        </div>
        <div class="modal-footer">
          <button  type="submit" class="btn btn-default">Valider</button>
          <button  value="" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
    </form>
  </div>
</div>

【讨论】:

  • 非常感谢兄弟,但有一个小问题http://127.0.0.1:8000/ges/3/update/ 向我显示 inpute 中的数据,但 modal 并未显示在真正的页面中,这意味着当我包含 modal.html 时
  • 它成功了兄弟,非常感谢你,我加了type:'GET'hhhhhhh 非常感谢你
  • jQuery .ajax 默认使用GET 方法,所以这不应该是问题。无论如何,我很高兴听到它对你有用!
【解决方案2】:

一个不错的选择是使用Vue.js 框架来构建组件并动态填写表单。

我非常喜欢 Vue.js,并且我构建了一个应用程序来解决您的问题。

我会一步一步解释我做了什么。

1。让我们用一些数据来模拟你的对象

views.js

from django.shortcuts import render


def home(request):
    users = [dict(id=1, first_name='Megan', last_name='Fox'),
             dict(id=2, first_name='Chester', last_name='Bennington')]
    if request.POST:
        for user in users:
            if user['id'] == int(request.POST.get('id')):
                user['first_name'] = request.POST.get('firstName')
                user['last_name'] = request.POST.get('lastName')
    return render(request, 'index.html', {'users': users})

2。导入一个 Vue 内置的 EventBus

我们将需要那个事件总线来显示模式。事件总线是将事件从一个组件“传输”到另一个组件的组件。所以我们可以在全局范围内监听和发出事件。

vue-bus.js

const EventBus = new Vue();
Object.defineProperties(Vue.prototype, {
    $bus: {
        get: function () {
            return EventBus;
        }
    }
});

3。使用 Vue 构建一个 row 组件来显示您的数据。

我将您的数据更改为 firstNamelastName 以便更好地解释。

此组件使用数据呈现您的行并设置编辑按钮以发出事件showModal 传递行中的数据。

components/row.js

Vue.component('row', {
    template: `
            <tr>
                <td>{{ firstName }}</td>
                <td>{{ lastName }}</td>
                <td>{{ id }}</td>
                <td><button @click="showModal">Edit</button></td>
            </tr>
        `,
    props: ['firstName', 'lastName', 'id'],
    methods: {
        showModal: function() {
            this.$bus.$emit('showModal', this.firstName, this.lastName, this.id);
        }
    }
});

4。使用 Bootstrap 构建 modal 组件

该组件在index.html 上使用x-template 来呈现其内容。在这个组件上,您只需要一个 showModal 事件的侦听器,因此当模式打开时,它将填充 row 内容。

components/modal.js

Vue.component('modal', {
    template: '#modal-template',
    data: function () {
        return {
            firstName: '',
            lastName: '',
            id: 0
        }
    },
    mounted: function () {
        this.$bus.$on('showModal', function (firstName, lastName, id) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.id = id;
        }.bind(this));
    }
});

5。构建你的 Vue.js 应用

如果您查看Vue.js docs,您将了解它是如何工作的。基本上,它会将您的应用程序安装在 id 为 #app 的元素中。

这里我只是在监听showModal事件,所以当这个事件发出时,模态框就会出现。

app.js

new Vue({
    el: '#app',
    data: {
        showModal: false
    },
    mounted: function () {
        this.$bus.$on('showModal', function () {
            this.showModal = true;
        }.bind(this));
    }
});

6。一些 CSS 让它漂亮

css/styles.css

table {
    margin: 20px;
}

td {
    padding: 10px;
    border: 1px solid #ccc;
}

.modal-mask {
    position: fixed;
    z-index: 9998;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, .5);
    display: table;
    transition: opacity .3s ease;
}

.modal-container {
    transition: all .3s ease;
}

.modal-enter {
    opacity: 0;
}

.modal-leave-active {
    opacity: 0;
}

7。最后,HTML

所以,我在这里做的是迭代用户列表,用用户数据填充行。

正如我之前所说,模态模板位于x-template 中。您需要对 Bootstrap 模态进行一些更改以使其工作,例如添加类 show 并更改 data-dismiss 属性以关闭模态。

数据是从 components/modal.js 上的侦听器填充的。绑定是在:value 上进行的。请参阅 Vue 网站上的 v-bind 文档以更好地了解其工作原理。

index.html

{% load static %}

<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>

<div id="app">
    <table>
        {% for user in users %}
            <tr is="row" first-name="{{ user.first_name }}" last-name="{{ user.last_name }}" :id="{{ user.id }}"></tr>
        {% endfor %}
    </table>
    <modal v-show="showModal" @close="showModal = false"></modal>
</div>

<script src="http://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="//unpkg.com/vue"></script>
<script type="text/x-template" id="modal-template">
    <transition name="modal">
        <div class="modal-mask">
            <div class="modal-container">
                <div id="myModal" class="modal show" role="dialog">
                    <div class="modal-dialog">
                        <form method="post" action=".">
                            {% csrf_token %}
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" @click="$emit('close')">&times;</button>
                                    <h4 class="modal-title">Edit User</h4>
                                </div>
                                <div class="modal-body">
                                    <label for="name">First Name:</label>
                                    <input type="text" class="form-control" name="firstName" :value="firstName" />
                                    <label for="lastName">Last Name:</label>
                                    <input type="text" class="form-control" name="lastName" :value="lastName" />
                                    <input type="hidden" name="id" :value="id" />
                                </div>
                                <div class="modal-footer">
                                    <button type="submit" class="btn btn-primary">Save</button>
                                    <button type="button" class="btn btn-default" @click="$emit('close')">Close</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </transition>
</script>
<script type="text/javascript" src="{% static 'vue-bus.js' %}"></script>
<script type="text/javascript" src="{% static 'components/row.js' %}"></script>
<script type="text/javascript" src="{% static 'components/modal.js' %}"></script>
<script type="text/javascript" src="{% static 'app.js' %}"></script>
</body>
</html>

结果

当我们点击Edit:

然后我们编辑数据:

然后保存:

【讨论】:

  • 非常感谢您的回答,但是您的代码太难了,我认为@Martin 它是更好的简单代码
猜你喜欢
  • 1970-01-01
  • 2021-10-22
  • 2012-12-19
  • 2021-05-20
  • 2018-12-26
  • 2013-01-26
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
相关资源
最近更新 更多