我需要一些帮助在django中构建动态formset。我知道有些javascript是必需的。我不是javascript专家。但我发现了一些示例代码,我正在努力使其适合我的特定表单。当我单击添加按钮时没有任何反应。我对如何前进感到茫然。有什么建议吗?
模型适用于与会者事件注册。客户可以注册多人参加活动 尝试获取添加与会者按钮。
# models.py
class Customer(models.Model):
event = models.ForeignKey(Event)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
address1 = models.CharField(max_length=60)
address2 = models.CharField(max_length=60, blank=True)
city = models.CharField(max_length=30)
state = models.CharField(max_length=2)
zipcode = models.CharField(max_length=5)
class Attendee(models.Model):
event = models.ForeignKey(Event)
sponsor = models.ForeignKey(Customer)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
# forms.py
CustomerFormset = inlineformset_factory(Customer, Attendee, form=AttendeeForm, exclude=('event'), extra=2)
# templates/register.html
<form action="/enroll/register3/{{ event.id }}/" method="post">{% csrf_token %}
<p> Sponsor information: </p>
<table>
{{ customer }}
</table>
<hr>
<p> Students Attending: </p>
{% for attendee in attendees.forms %}
<div class="formgroup">
{{ attendee }}
{% if attendee.nested %}
{% for formset in attendee.nested %}
{{ formset.as_table }}
{% endfor %}
{% endif %}
</div>
{% endfor %}
<div>
Nothing happens when 'add_more' is clicked. ??
<input type="button" value="Add Attendee" id="add_more">
<input type="submit" value="Submit">
</div>
</form>
<script>
$('#add_more').click(function() {
//cloneMore('div.table:last', 'service');
cloneMore('div.table:last', 'formgroup');
});
function cloneMore(selector, type) {
console.log('cloneMore');
var newElement = $(selector).clone(true);
var total = $('#id_' + type + '-TOTAL_FORMS').val();
newElement.find(':input').each(function() {
var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
});
newElement.find('label').each(function() {
var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-');
$(this).attr('for', newFor);
});
total++;
$('#id_' + type + '-TOTAL_FORMS').val(total);
$(selector).after(newElement);
}
</script>
答案 0 :(得分:1)
看起来您从this question获取了javascript,但是您没有调整HTML结构。
正如我在你的代码片段中看到的那样(看起来它也会产生高度无效的html,即div中的tr):
{% for attendee in attendees.forms %}
<div class="formgroup">
{{ attendee }}
{% if attendee.nested %}
{% for formset in attendee.nested %}
{{ formset.as_table }}
{% endfor %}
{% endif %}
</div>
{% endfor %}
他的:
{{ serviceFormset.management_form }}
{% for form in serviceFormset.forms %}
<div class='table'>
<table class='no_error'>
{{ form.as_table }}
</table>
</div>
{% endfor %}
如果你想要相同的javascript代码段,那么你应该拥有相同的HTML结构。你在JS中做的第一件事是传递div.table:last作为选择器,但你的HTML中没有div.table。
您最好的选择是尝试自己制作JavaScript。作为网页开发者,javascript将为您提供很多帮助。