[Fixed]-How to use TextInput widget with ModelChoiceField in Django forms?

0👍

In my case, I had to change the sku_number field to Product object’s id. This had to be done before clean(). As seen in this answer, __init__() should be used to modify data before it reaches clean().

class SkuForm(forms.Form):
    sku_number = forms.ModelChoiceField(queryset=Product.objects.all(), 
                                        widget=forms.TextInput())
    extra_field = forms.CharField(required=True)

    def __init__(self, data=None, *args, **kwargs):
        if data is not None:
            data = data.copy() # make it mutable
            if data['sku_number']:
                obj = get_object_or_404(Product, batch_name=data['sku_number'])
                data['sku_number'] = obj.id
        super(SkuForm, self).__init__(data=data, *args, **kwargs)
👤Suraj

1👍

You can easily do that in the form clean() method.

I.e.

from django.shortcuts import get_object_or_404

class SkuForm(forms.Form):
    sku = forms.CharField(required=True)
    extra_field = forms.CharField(required=True)

    def clean(self):
        # If you're on Python 2.x, change super() to super(SkuForm, self)
        cleaned_data = super().clean()
        sku = cleaned_data['sku']
        obj = get_object_or_404(Product, sku_number=sku)
        # do sth with the Product

Leave a comment