[Answered ]-How to display multiple forms of a single model in Django templates?

3👍

The easiest way to do this is to use a formset (also see model formsets).

For your Note model and NoteEditForm you could do something like this. You’d usually put this wherever you’ve defined your NoteEditForm but it can go in another file, such as views.py.

from django.forms import modelformset_factory
NoteEditFormSet = modelformset_factory(Note, form=NoteEditForm)

Using NoteEditFormSet in a view and template is almost the same as using a regular form, but there are a few differences to be aware of if you want to do anything complicated so have a look at the docs (view and template). If that’s not clear enough, add a few details of what you’re trying to do in your view and template and I’ll try to help.

By default the formset will use Note.objects.all() as its queryset, which is what you say you want, but you can change that (details are covered in the docs).

Update:

To save an individual Note with an AJAX request I would add a second view to handle those requests. So if your formset for all Notes is served by a view at /notes/, you could add a view to handle your AJAX request at /notes/<note_id>/ (obviously just an example, adjust to fit your URL structure).

Then your JS on the /notes/ page is responsible for serializing the data for a single note and making the request to /notes/<note_id>/ (remember the CSRF token).

The HTML inputs generated for the formset have their IDs prefixed with something like id_form-<number>- and there are hidden inputs containing Note primary keys which will let you work out which ID prefix applies to each note.

👤Kevin

-1👍

I would think about doing it like this

{% for note in Notequeryset %}
    <form action={% url 'url_name_to_form' pk={{note.pk}} %}>
    {{form.as_p}}
    </form>
{% endfor %}

Let me know what you think

👤A.Lang

Leave a comment