Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

how to override a ModelChoiceField in order to add FKs directly in a TextInput?

133 views
Skip to first unread message

snfctech

unread,
Jun 25, 2011, 9:49:00 PM6/25/11
to Django users
I can get text inputs rendered fine by setting the widget to a
TextInput like so:

myrelation = ModelChoiceField(MyRelatedClass.objects.none(),
widget=TextInput)

But I still get ModelChoiceField validation errors on validate:

'Select a valid choice. That choice is not one of the available
choices.'

Can I disable the ModelChocieField validation or override it? Or can
I override the ModelChoiceField entirely? I tried using

myrelation = IntegerField(widget=TextInput) but get:

Cannot assign "123": "MyClass.relation" must be a "MyRelatedClass"
instance.

Any tips would be greatly appreciated.

Tony

Martin Pajuste

unread,
Jun 29, 2011, 10:59:13 AM6/29/11
to django...@googlegroups.com
Since ModelChoiceField validates that the given id exists in the queryset, there can be no valid choices when you use MyRelatedClass.objects.none().

Try MyRelatedClass.objects.all() or filter by some attribute. If the queryset depends on some user input or conditions you can use something like:

def __init__(self, some_value, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    qset= MyRelatedClass.objects.filter(some_field=some_value)
    self.fields['myrelation '].queryset = qset


Martin

snfctech

unread,
Jul 6, 2011, 5:10:25 PM7/6/11
to django...@googlegroups.com
Hi, Martin.

Thanks for your reply.

I wound up using IntigerFields and getting around the "relation must be an instance" error by adding clean methods that returned instances, e.g.

def clean_myfield(self):
    data = self.cleaned_data['myfield']
                  data = MyRelatedClass.objects.get(pk=data)
         return data 
 
 
Reply all
Reply to author
Forward
0 new messages