[Answered ]-Initializing a queryset for a dropdown field in a ModelForm

1๐Ÿ‘

I may have figured out how to do this properly. I changed req to reqs then I passed reqs into the formset in the POST method and tweaked it a little bit. Now the get_context_data in the views look like this:

def get_context_data(self, **kwargs):
        ctx=super(TransferAddView,self).get_context_data(**kwargs)
        ctx['req'] = MaterialRequisition.objects.get(pk=self.kwargs['req'])
        req = list(MaterialRequisitionItems.objects.filter(requisition=ctx['req']).values_list('item', flat=True))
        ctx['item'] = Item.objects.filter(item__in=req)
        if self.request.method == 'POST':
            ctx['form']=TransferModelForm(self.request.POST)
            ctx['inlines']=TransferInlineFormSet(self.request.POST, form_kwargs={'reqs': list(MaterialRequisitionItems.objects.filter(requisition=ctx['req'].pk).values_list('item', flat=True))})
            ctx['form'].fields['transferStatus'].initial = 0
        else:
            ctx['form']=TransferModelForm()
            ctx['form'].fields['transferStatus'].initial = 0
            ctx['inlines']=TransferInlineFormSet(form_kwargs={'reqs': list(MaterialRequisitionItems.objects.filter(requisition=ctx['req'].pk).values_list('item', flat=True))})
        return ctx

Leave a comment