How can I render a Django Formset with some data for update process?

I am using Dajngo formset with inlineformset_factory What I need it when the user click in the update like It should render formset with the value. This is the code I did but nothing works: This is how I create a formset

OrderItemFormset = inlineformset_factory(
    Order, OrderItem, fields='__all__', extra=1, can_delete=False)

And here how I tried to render the formset with the queryset=my_query_set.

if 'id' in kwargs.keys():
            order = Order.objects.get(id=kwargs.get('id'))
            order_items = OrderItem.objects.filter(order_id=kwargs.get('id'))
        else:
            order = None
            order_items = None
        order_form = OrderForm(instance=order)
        print(order_items)
        order_item_form = OrderItemFormset(queryset=order_items)
    

When I click in the update link Django render the Parent form with the data I need, but this does not work with formset it just give me one row with empty data.

After some trying to solve my problem I found that I use queryset, and I think I should use instance instead. And the other thing is that the instance was from OrderItem model and instead it should be from the Order model so the code should look like this.

def get(self, request, *args, **kwargs):
        if 'id' in kwargs.keys():
            order = Order.objects.get(id=kwargs.get('id'))
        else:
            order = None
        order_form = OrderForm(instance=order)
        order_item_form = OrderItemFormset(instance=order)
        orders = Order.objects.all()
        context = {'order_form': order_form,
                   'order_item_form': order_item_form, 'orders': orders}
        return render(request, self.template_name, context)

Back to Top