Reputation: 43
I have been RTFM for maybe three weeks solid and I cannot figure out how to do this. If I ever get good at this then I promise I will write a Django for Dummies book, the documentation is incomprehensible!
I have a simple note taking app with an index page that displays the title of each note in the database. I just want each item in the list to have a checkbox so you can select one or multiple notes and then press a delete button, redirect to an 'Are you sure you want to delete... "x, y and z" notes? page, with confirm or deny. Then back to the index list. Just like in the admin app.
I have deduced that I should need a modelformset layed out in a table as each object title and it's checkbox should constitute an individual form.
I have tried many approaches. The latest looks like this. It's not throwing any errors as it stands(I had a widgets attribute set in the forms.py function but it didn't like that. I took it out just to see if it would display something.) But it is not displaying anything at all. I also think the select_note_function should probably be a class instead. All the docs I can find explain CharFields and string inputs. I cant find a single fully fledged example of how to get widgets controlling the database.
forms.py:
from django import forms
from django.forms.models import modelformset_factory
from django.forms.widgets import CheckboxInput
from models import Note
def select_note_formset():
SelectNote = modelformset_factory(Note)
Form = modelformset_factory(
Note,
form=SelectNote,
fields='title',
)
models.py:
def selection_index(request):
form = select_note_formset()
if request.method == 'POST':
formset = form(request.POST)
if formsest.is_valid():
pass
else:
formset=form
return render_to_response('select_index.html', {'formset':formset})
template:
<form method="post" action="">
{{ formset.management_form }}
<table>
{% for form in formset %}
{{ form }}
{% endfor %}
</table>
</form>
For all I know I could be barking up the totally wrong tree. If someone could spell this out I would appreciate it terribly!
Upvotes: 0
Views: 1222
Reputation: 1485
I have a gist for this, I just figured it out for myself last week:
https://gist.github.com/bjb/5717314
In a nutshell: make a new field type for a model that includes a hidden input for the model id and validates to the full model, put it in your form, and make a formset of these forms.
In my own search for the solution, people told me to use CheckboxSelectMultiple, but I didn't like that route because I would have had to put each model description into a single string. I wanted to list the model attributes as columns, and also (I haven't tried this yet) optionally show some related models after each model. So I wanted more control over the display than CheckboxSelectMultiple would have given me.
After a year or two you get the hang of the documentation ; -). Also, don't be afraid to read the source code of django.
Upvotes: 1