Django form with multiple checkboxes

I am really new to Django! I have a page that displays items with checkboxes next to them. The number of items/checkboxes varies. When a button is pressed, I want the corresponding checked item to be modified.

So far, I have tried to wrap it all in one form:

<form method="post">
{% csrf_token %}
{% for event in items %}
    {{ event.eventID }}
    <input type="checkbox" value="{{ event.eventID }}" name="choices">
{% endfor %}
<button type="submit">Approve</button>
</form>

I want to collect them in a Django form field. I am trying to use ModelMultipleChoiceField:

class ApproveEventForm(forms.Form):
    choices = forms.ModelMultipleChoiceField(queryset = Event.objects.all(), widget=forms.CheckboxSelectMultiple())

And in my views, I want to edit the selected items:

def approve_event(request):
if request.method == "POST":
    form = ApproveEventForm(request.POST)
    print(form.errors)
    if form.is_valid():
        for item in form.cleaned_data['choices']:
            item.approved = True
            item.save()
else:
    form = ApproveEventForm()
    unapproved = Event.objects.filter(approved=False)
    return render(request, 'app/approve_event.html', {'items': unapproved, 'form': form})

My form is not valid and form.errors prints: choices "" is not a valid value for a primary key.
How can I fix this? Or is there another way to access the selected items?

Edit: passed the form to the template.

Upvotes: 1

Views: 8576

Answers (1)

Managed to fix it using MultipleChoiceField instead of ModelMultipleChoiceField. Then populated the choices with existing event IDs and passed it to the template.

In forms:

choices = forms.MultipleChoiceField(widget = forms.CheckboxSelectMultiple())

In views:

form.fields['choices'].choices = [(x.eventID, "Event ID: " + x.eventID) for x in unapproved]

Had to change some of the logic for finding and editing Event objects too.

Upvotes: 1

Related Questions