【问题标题】:Add dynamic fields in forms (Django)在表单中添加动态字段(Django)
【发布时间】:2015-06-11 10:52:11
【问题描述】:

我有一个表单定义为:

class testForm(forms.Form):
    book = forms.CharField(label='Book:', widget=forms.TextInput())

我正在尝试在表单中添加动态字段。也就是说文本框旁边有一个按钮,如果点击按钮,在原来的文本框下面会出现一个新的文本框,这个表单只是一个表单。

在我的模板中:

<table>
   {{form.as_table}}
   <table class = 'request'>
         {{form.as_table}}
   {#  <input type="button" onclick="addTextBox()"/>#}
   {#   <span id="response"></span>#}
   </table>
    <br>
    <input type="submit" value="Submit">
 </table>

我不想更改我的模板,所以我正在尝试使用js来完成它。

var countBox = 1;
var boxName = 0;
function addTextBox(){
   boxName = "textBox"+countBox;
   document.getElementById('response').innerHTML+='<br/><input type="text" 
   id="'+boxName+'" value="'+boxName+'" "  /><br/>';
   countBox += 1;
 }

但它没有做我想要的,有人有什么想法吗?

【问题讨论】:

  • 附上你现在所拥有的截图“它没有按照我的意愿去做”

标签: javascript django forms dynamic


【解决方案1】:

我不知道这是否适合您,但您可以尝试使用一个带有一个表单的页面,该页面会添加所有新书并显示一个附加表单。 基本上,当您通过表单添加新书时,它将使用 ajax 刷新页面,表单不会去任何地方,您的书将在数据库中,因此将显示在同一页面中。

这是基本代码: 视图.py:

def all(request):
    obj = Books.objects.all()
    ...

模板:

<div id='books'>
{% for o in objs %}
    {{ o }}
{% endfor %}
    <form method='POST' action='#' enctype='multipart/form-data'>
        {% csrf_token %}
        // your form
        <table>
            {{form.as_table}}
        <table class = 'request'>
            {{form.as_table}}
        {#  <input type="button" onclick="addTextBox()"/>#}
        {#   <span id="response"></span>#}
        </table>
        <br>
        // end of your form
        <input type="submit" value="Submit">
        </table>
        <input class="ui button" type='submit' value='Add Skill' /> 
    </form>
</div>
<script type="text/javascript">
        $("#addform").submit(function(e) {
          var url = $(this).attr('action');
          var formData = new FormData(this);

            $.ajax({
                   type: "POST",
                   url: url,
                   data: formData,
                   async: false,
                   cache: false,
                   contentType: false,
                   processData: false,
                   success: function(data)
                   {
                   $("#books").load("# #books");
                   }
                 });
                e.preventDefault();

            });    
</script>

如果我遇到同样的问题,我会同意,但这当然是你的决定。

【讨论】:

  • 谢谢,但这不是我需要的。我不想循环从数据库中获取数据,而是尝试在前端动态添加“charFields”并输入用户的数据然后提交表单。从前端获取数据并存储到数据库中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 2011-09-02
相关资源
最近更新 更多