我想尝试在模板中添加行,然后将其保存。 在模板中,单击“添加行”按钮将生成一个新行,然后“提交”将保存此表单。 我想做的是用户可以添加行数并保存。但是在CreateView中,它总是只获得第一行。 我尝试了很多方法,但仍然不知道。
例如,我有第一行
<th><input type="checkbox" name="record"></th>
<th><p id="counter"> 1 </p></th>
<th><input type="number" name="quantity" step="any" required id="id_quantity"></th>
点击“添加”后,以下HTML代码将添加到第一行之后
<th><input type="checkbox" name="record"></th>
<th><p id="counter"> 1 </p></th>
<input type="number" name="quantity-2" step="any" required="" id="id_quantity-2">
这是我的模板:
<form method="post" class="uniForm" action="">
{% csrf_token %}
<table class="table table-striped table-condensed" id="dyeing">
<thead>
<tr>
<th>choice</th>
<th>number</th>
<th>ticket</th>
</tr>
</thead>
<tbody>
<tr>
<th><input type="checkbox" name="record"></th>
<th><p id="counter"> 1 </p></th>
<th>...</th>
</tr>
</tbody>
</table>
<div class="col-sm-12">
<input type="button" id="btn" value="add"/>
</div>
<div class="col-sm-12">
<input type="submit" value=" save" class="">
</div>
</form>
jQuery部分是:
<script>
$("#btn").click(function () {
//var markup = "<tr><td><input type='checkbox' name='
addrow($('#dyeing > tbody:last-child'))
});
function addrow(selector) {
new_row = selector.clone(true)
counter = parseInt(new_row.find('#counter').text(), 10) + 1
new_row.find(":input").each(function () {
var name = $(this).attr('name');
if (counter == 2) {
name = name + '-' + counter
} else {
name.replace('-' + (counter - 1), '-' + counter)
}
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id})
})
new_row.find('#counter').text(counter)
selector.after(new_row)
counter++
}
我的views.py:
class CreateTicketForm(generic.CreateView):
...
def form_valid(self, form):
# only get the first row
print(form)
return super().form_valid(form)
答案 0 :(得分:0)
为我自己回答问题。 这是代码。 form.py:
class TicketForm(forms.ModelForm):
class Meta:
model = ...
fields = "color"
views.py:
def create_ticket(request):
...
if request.method == "POST":
forms = [
TicketForm(dict(color=c, ))
for c, q, n in zip(
request.POST.getlist("color"),
)
]
if all(forms[i].is_valid() for i in range(len(forms))):
for form in forms:
form.save()
return HttpResponseRedirect(success_url)
else:
form = TicketForm()
return render(request, 'template', {'form': form})
而jQuery部分是:
$("#btn").click(function () {
addrow($('#dyeing > tbody:last-child'))
});
function addrow(selector) {
var new_row = selector.clone(true)
var counter = parseInt(new_row.find('#counter').text(), 10) + 1
new_row.find('#counter').text(counter)
selector.after(new_row)
}