动态Django表单

时间:2016-04-20 14:08:53

标签: ajax django django-forms django-templates

我想在django表单中创建下拉列表。 一种方法是获取选项并将其从views.py传递给模板 其他方式是通过forms.py,但我不知道该怎么做。虽然这样做的代码可用,但它不适用于我,因为我想根据用户生成选项它登录(这意味着使用request参数)。你能建议怎么做吗? 传递途径views.py的第一种方法工作到生成下拉列表的程度,但我无法从请求中获取所选选项的值。它给出一个空值。 这是我的代码: 模板

<script type="text/javascript">

$(document).ready(function() {
    $('#remove_form').submit(function() { // catch the form's submit event
        $.ajax({ // create an AJAX call...
            data: $(this).serialize(), // get the form data
            type: $(this).attr('method'), // GET or POST
            url: '/remove/', // the file to call
            success: function(response) { // on success..
                $('#test').html("<p style='color:green;margin-left:40%;margin-right:40%;'>Submitted!</p>"); // update the DIV

            },
            error: function(e, x, r) { // on error..
                $('#err').html(e); // update the DIV
            }
        });
        return false;
    });
});

</script>

......
......

 <form method="POST" id="remove_form" action="">{% csrf_token %}
      <select id="remove">
      {% for i,p in dropdown %}      
        <option value="{{i}}">{{p}}</option>
      {% endfor %}
        </select>
        {{remove|crispy}}
         <input class="btn btn-primary" type="submit" value="Remove">
</form>

另请注意,我从一个视图渲染此表单,但数据进入另一个视图以通过ajax调用进行处理。

1 个答案:

答案 0 :(得分:0)

<select id="remove">

select代码采用name属性。

<select name="remove" id="remove">

然后你的表格有效。 http://codepen.io/C14L/pen/dMKqPE

相关问题