Ajouter des formulaire supplémentaires à un formset
Bonjour tout le monde,
J'essaye de mettre en place la possibilité d'ajouter de manière dynamique des formulaires dans un formset Django.
Pour ce faire j'utilise du Javascript, mais le problème que j'ai est le suivant : Si je clic sur mon bouton d'ajout, aucun nouveau formulaire n’apparaît.
Cela fait plus d'une semaine que je suis dessus et je n'arrive toujours pas à avoir de résultat sur la mise en place de cette fonctionnalité.
J'ai un fichier forms.py qui ressemble à cela :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class PublicationForm(forms.Form):
def __init__(self, *args, **kwargs):
super(PublicationForm, self).__init__(*args, **kwargs)
class Meta:
model = Publication
fields = ['title', 'pub_id', 'category', 'cover']
class DocumentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(DocumentForm, self).__init__(*args, **kwargs)
class Meta:
model = Document
fields = ['publication', 'language', 'format', 'title', 'upload']
DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1, max_num=4) |
Puis, un fichier views.py qui comporte la classe suivante :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class PublicationCreateView(CreateView):
""" Create publication with document form through formset """
model = Publication
template_name = 'publication_form.html'
def get_context_data(self, **kwargs):
context = super(PublicationCreateView, self).get_context_data(**kwargs)
context['DocumentFormSet'] = DocumentFormSet(self.request.POST or None, self.request.FILES or None, prefix='doc')
return context
def form_valid(self, form):
context = self.get_context_data()
document = context['DocumentFormSet']
if document.is_valid():
self.object = form.save()
document.instance = self.object
document.save()
return super(PublicationCreateView, self).form_valid(form)
def get_success_url(self):
return reverse('publication-list-crud') |
Et enfin, j'ai un template HTML avec une partie JS :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
{% block main %}
<h2>{{ title }}</h2>
<div class="row publication-create">
<form method="post" action="" enctype="multipart/form-data" novalidate>
{% csrf_token %}
{{ form.management_form }}
<fieldset>
<legend class="title"><span class="name">{% trans 'Publication form' %}</span></legend>
<div class="row">
<div class="col-xs-6">
{{ form.category|as_crispy_field }}
</div>
<div class="col-xs-6">
{{ form.pub_id|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-xs-6">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-6">
{{ form.cover|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-xs-12">
{{ form.description|as_crispy_field }}
</div>
</div>
</fieldset>
<fieldset>
<legend class="title"><span class="name">{% trans 'Document form' %}</span></legend>
{{ DocumentFormSet.management_form }}
{% for form in DocumentFormSet.forms %}
<div class='table'>
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
{% endfor %}
<input type="button" value="Add More" id="add_more">
<script>
$('#add_more').click(function () {
cloneMore('div.table:last', 'service');
});
</script>
</fieldset>
<br>
<input type="submit" class="btn btn-default" value="{% trans 'Save' %}"/>
<a href="{{ request.META.HTTP_REFERER }}" class="btn btn-default">{% trans 'Cancel' %}</a>
</form>
</div>
{% endblock main %} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
function cloneMore(selector, type) {
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);
} |
Pouvez-vous me dire ce qui pourrait poser problème dans mon code ?
Je ne trouve aucun solution à mon problème pour l'instant ..
Merci d'avance,