Today I was creating the submission form for the new iBegin.com homepage. In this we use a lot of JavaScript to make the process more clean. One such use, was an autocomplete on Cities and Categories. To do this, and to keep validation, you need to use a ModelChoiceField, but using a ModelChoiceField with a TextInput doesn’t work. So, I give you an InlineModelChoiceField in Django.
1234567891011121314
fromdjangoimportnewformsasformsclassInlineModelChoiceField(forms.ModelChoiceField):def__init__(self,*args,**kwargs):kwargs['widget']=kwargs.pop('widget',forms.widgets.TextInput)super(InlineModelChoiceField,self).__init__(*args,**kwargs)defclean(self,value):ifnotvalueandnotself.required:returnNonetry:returnself.queryset.filter(name=value).get()exceptself.queryset.model.DoesNotExist:raiseforms.ValidationError("Please enter a valid %s."%(self.queryset.model._meta.verbose_name,))