我需要一些帮助在 django 中构建动态表单集。我知道需要一些 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>