【问题标题】:Call Django view to update model data upon row button click in HTML调用 Django 视图以在 HTML 中单击行按钮时更新模型数据
【发布时间】:2015-12-17 03:40:36
【问题描述】:

我目前是 Django 和 Web 开发的新手。

我在 HTML 模板中显示了一些数据。数据采用表格行格式。用户可以从每一行编辑数据(从文本和下拉菜单)。我想调用 django 视图以在单击与该行关联的按钮时更新相应模型数据库中的该行数据。

这是我的 HTML 代码:

<table>
    <tr>
        <th>Candidate Name </th>
        <th>Change Application Status </th>
        <th>Submit </th>
    </tr>
    {% for eachApplication in myCompanyApplications %}
        <td>
            <a href="/candidate/{{ eachApplication.candidateId }}/">{{  eachApplication.candidateName }}</a></td>
        <td>
            <select>
                {% for choice in list.currentApplicationStatus %}
                    <option {{choice.0}}>{{choice}}</option>
                {% endfor %}
            </select>
        </td>
        <td><input type="submit" class="btn" value="Commit" name="mybtn"></td>
    </tr>
    {% endfor %}
</table>

我想检测变化(applicationStatus change etc)

单击一个按钮应该调用一个视图,并且该视图将更改相应的Django model

如果有更好的方法请提及。

我们将不胜感激。

谢谢:)

【问题讨论】:

    标签: jquery python html django django-models


    【解决方案1】:
    1. 将您的第一个 for 循环 tds 放入表单中
    2. 给每个表单一个动态ID,比如form-{{ eachApplication.candidateId }}
    3. 使用 ajax 将数据发布到表单提交的视图中,

    这样的事情可能会对你有所帮助:

    $('body').on('submit',"#formid",function(event) {
                 event.preventDefault();
                 url = 'your  django view url '
                 $.ajax({
                        type: "POST",
                        url: url,
                        data: $(this).serialize(), // serializes the form's elements.
                        success: function(data){
                            //do something on successs
                        }
                        },
                        error:function(data){
                            //do something on error
                        }
                      });
             });
    

    【讨论】:

    • 如果你使用类来定位表单会​​更好
    • 感谢您的回复。如果卡在某个地方,我会尝试添加它并返回。
    【解决方案2】:
    $(function  () {
    $('#my-form').submit(function(event) {
        $.ajax({
            url: 'your View URL',
            type: 'form method (POST,GET,HEAD,......)',
            dataType: 'html',
            data: {
                'Value':$('#input').val(),
                'csrfmiddlewaretoken':$("input[name=csrfmiddlewaretoken]").val(),
    
            },
            success:onSuccess,
        });
        function onSuccess (data, textStatus, jqXHR) {
            //do something on successs
        };
    
    });
    

    });

    你可以像你一样添加一个错误函数:D

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 2021-10-03
      • 2017-03-06
      相关资源
      最近更新 更多