【问题标题】:Form with button adding new field to it带有按钮的表单向其添加新字段
【发布时间】:2016-05-01 01:20:51
【问题描述】:

我想知道用 Django 创建动态表单的最佳方法是什么。

假设有一种训练形式可以包含一些锻炼。锻炼次数未指定 (1+)。如何使用添加新锻炼的按钮创建这样的表单?

编辑:

我的后端是用 Django/Python 编写的。 到目前为止,我的模型如下所示:

class WorkoutForm(forms.Form):
    name = forms.CharField(max_length = 45)
    description = forms.CharField(widget = forms.Textarea)

class TrainingForm(forms.Form):
    name = forms.CharField(max_length = 45)
    all_workouts = Workout.objects.all()
    description = forms.CharField(widget = forms.Textarea)
    selected_workouts = forms.MultipleChoiceField(required=False,
        widget=forms.SelectMultiple, choices=[(o.id, o.name) for o in all_workouts])

但我想将其更改为动态表单,并在单击添加按钮后添加新的锻炼字段。

【问题讨论】:

  • 你不需要 django。你可以只使用简单的 jQuery。
  • @PraveenKumar 他们不是在问表单集,特别是内联模型表单集吗? adamura88,在你的情况下,锻炼是一个相关的模型吗?请粘贴您的型号代码。
  • @jpic 意思是,我的回答没有帮助?
  • 我不确定,验证取决于他们的数据模型。

标签: jquery django forms


【解决方案1】:

这样的事情对你有帮助吗?

$(function () {
  $("#add").click(function (e) {
    e.preventDefault();      // Make sure nothing happens.
    $(".master")
      .clone()                // Clone this
      .removeClass("master")  // Remove the master class
      .find("input").attr("name", "workout[]").end() // Change the input name
      .appendTo("form");      // Append it to the form.
  });
});
label {display: block;}
.master {display: none;}
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<form action="">
  <label class="master">
    <strong></strong>
    <input type="text" />
  </label>
  <a href="#" id="add">Add New</a>
  <label>
    <strong></strong>
    <input type="text" name="workout[]" />
  </label>
</form>

【讨论】:

    【解决方案2】:

    我认为这样的方法也可以,具体取决于您的需要。

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form>
      <div id="workouts">
        <div class="workout" id="workout1">
          <label>Workout:</label>
          <input type="text">
        </div>
      </div>
    
      <button id="addWorkout" type="button">Add</button>
    </form>
    <script>
      $("#addWorkout").on("click", function(e) {
        e.preventDefault();
        var last = $("#workouts").last().attr("id")
        template = "<div class='workout' id='workout" + parseInt(last[-1])+1 + "'><label>Workout:</label> <input type='text'>"
        $("#workouts").append(template);
      });
    </script>

    【讨论】:

    • 好的,但是在 Django 端怎么做呢?
    • @adamura88 我可以给你一个想法,基本上你需要在 trainingform 类中编写一个类似add 函数的功能,该函数将调用会创建新字段的锻炼表单类(我假设),然后是另一个 update 函数,它将更新锻炼字段的数量
    猜你喜欢
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    相关资源
    最近更新 更多