How do i pass list to ModelMultipleChoiceField

209 views Asked by At

This is the participant selection form

class EventFormAdmin(ModelForm):

name = forms.TextInput(attrs={'class':'form-control'}),
manager = forms.Select(attrs={'class':'form-select'}),     
venue = forms.Select(attrs={'class':'form-select'}),
event_date = forms.TextInput(attrs={'class':'form-control'}),
participants = forms.ModelMultipleChoiceField(
    
    **queryset=Participant.objects.filter().values(participant_list),** #filter for participants who applied for a specific event
    widget=forms.CheckboxSelectMultiple
),
description = forms.Textarea(attrs={'class':'form-control'}),

class Meta:
    model = Event 
    fields = ('name', 'manager', 'venue', 'event_date', 'participants', 'description')

How do i put participant_list in ModelMultipleChoiceField in the function, I described the filter by values that I try to pass to the form field

def update_event(request, event_id):
event = Event.objects.get(pk=event_id)
participant_list = Participant.objects.filter(
    event = event_id
)
if request.user.is_superuser:
    form = EventFormAdmin(request.POST or None, instance=event)
else:
    form = EventForm(request.POST or None, instance=event)

if form.is_valid():
        form.save()
        return redirect('all_events')
return render(request, 
    'events/update_event.html', {
    'participant_list':participant_list,
    'event': event,
    'form':form
    })

Thanks

1

There are 1 answers

3
Rajeel Rajput On

use this code right before the form.is_valid() condition

form.fields.get('participant_list').queryset=participant_list