Home > Software design >  Django how to use a ModelChoiceField in a formset_factory
Django how to use a ModelChoiceField in a formset_factory

Time:02-01

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.

(edit added the models.py) models.py

class Order(Model):
    user = ForeignKey(User, on_delete=SET_NULL, null=True)
    fee = ForeignKey(Fee, on_delete=SET_NULL, null=True)
    route = ForeignKey(Route, on_delete=SET_NULL, null=True)
    price_rate = ForeignKey(PriceRate, on_delete=SET_NULL, null=True)
    pallet_amount = IntegerField()
    status = BooleanField()
    postal_code = CharField(max_length=6)
    city = CharField(max_length=255)
    street = CharField(max_length=255)
    delivery_from = DateTimeField()
    delivery_until = DateTimeField(null=True)
    created_at = DateTimeField(auto_now_add=True, blank=True)
    updated_at = DateTimeField(auto_now=True)
    deleted_at = DateTimeField(null=True, blank=True)

views.py

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

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

forms.py

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

    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

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

template:

{% extends 'base.html' %}
{% block base %}
    <div >
        <div >
            <div >
                planner//route
                <div >
                    <form id="form-container" method="POST">
                        {% csrf_token %}
                        {{ form }}
                        {{ formset }}
                        <button id="add-form" type="button">Add Another Bird</button>
                        <button  onclick="window.history.back()">Cancel
                        </button>
                        <button  type="submit">Order</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

error:

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

The error occurs when i fill the formset with request.POST and then try to send the formset to the template.

I have tried an inlineformset and modelformset and didnt get it to work. ANY solution is welcome.

CodePudding user response:

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.

  • Related