Django how to use a ModelChoiceField in a formset_factory

I am trying to use a modelchoicefield from the form in a formset_factory but i dont understand the error and don't know how to solve it.

def routecreate_view(request):
    orderformset = formset_factory(OrdersRouteForm, can_delete=False, extra=1)
    if request.method == 'POST':
        form = RouteForm(request.POST)
        formset = orderformset(request.POST)
        if form.is_valid() and formset.is_valid():
            # process the data in form.cleaned_data as required

                             "You succesfully created an route.")
            return HttpResponseRedirect(reverse('planner.dashboard'))
        form = RouteForm()
        formset = orderformset()
    return render(request, 'planner/route.html', {'form': form, 'formset': formset})

class OrdersRouteForm(forms.ModelForm):
    route = ModelChoiceField(
        queryset=Order.objects.filter(status=1,, deleted_at=None),

    class Meta:
        model = Order
        fields = ("route",)

    def __init__(self, *args, **kwargs):
        super(OrdersRouteForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control m-2'

            self.fields['route'].label_from_instance = self.label_from_instance

    def label_from_instance(obj):
        return "pallets: %s, %s, %s, %s" % (obj.pallet_amount, obj.street,, obj.postal_code)


{% extends 'base.html' %}
{% block base %}
    <div class="container rounded bg-white mt-5 mb-5">
        <div class="row">
            <div class="col-md-5 border-right mx-auto">
                <div class="p-3 py-5">
                    <form id="form-container" method="POST">
                        {% csrf_token %}
                        {{ form }}
                        {{ formset }}
                        <button id="add-form" type="button">Add Another Bird</button>
                        <button class="btn btn-danger profile-button mt-3" onclick="window.history.back()">Cancel
                        <button class="btn btn-primary float-end mt-3" type="submit">Order</button>
{% endblock %}


Cannot assign "<Order: Order object (2)>": "Order.route" must be a "Route" instance.

I have tried alot and didn't get it to work. ANY solution is welcome.

The problem seemed to be with the modelform. I removed this from the code:

    class Meta:
        model = Order
        fields = ("route",)

I don't understand why this caused the problem and if anyone knows and can explain it please feel free to do so.

hope it helps anyone else with this problem.

Back to Top