1

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.

1
  • Why don't you send your form into the template. context = {'form':form}. I would personally instantiate the form at the beginning of the view just once: form = ApproveEventForm(request.POST or None), you don't have to instantiate it two times. Commented Nov 23, 2017 at 21:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.