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.
from django import newforms as forms class InlineModelChoiceField(forms.ModelChoiceField): def __init__(self, *args, **kwargs): kwargs['widget'] = kwargs.pop('widget', forms.widgets.TextInput) super(InlineModelChoiceField, self).__init__(*args, **kwargs) def clean(self, value): if not value and not self.required: return None try: return self.queryset.filter(name=value).get() except self.queryset.model.DoesNotExist: raise forms.ValidationError("Please enter a valid %s." % (self.queryset.model._meta.verbose_name,))
