On Thu, May 21, 2009 at 10:45:06AM +1000, Brian May wrote:
> A frequent problem people seem to have with Django[1] is the default
> interface for selecting foreign keys is slow and clumsy to use if there
> are lots of selections. To the best of my knowledge there is no solution
> included with Django.
>
> So I have created my own field type that is derived from the
> django.forms.CharField form type. The Clean method will look up the
> value in the db with the matching name, and return the result. Simple.
> Efficient. No need to repeatedly query the database/objects for the same
> data, if the same foreign key appears multiple times on the same form. I
> like it.
>
> The problem comes to using this with the admin interface. I created a
> class derived from django.db.models.ForeignKey that overrides the
> formfield method to use my field type. Unfortunately this does not work[2].
No answers, I will not use the forms interface then. Maybe that was the wrong
approach?
My current approach is to create my custom field type, like:
from django import forms
from microcomaustralia.zoph import models
=== cut ===
class Person_Field(forms.CharField):
def __init__(self, queryset=None, to_field_name=None, *args, **kwargs):
super(Person_Field, self).__init__(*args, **kwargs)
def clean(self, value):
value=super(Person_Field, self).clean(value)
if value in ('',None):
return None
s = value.split(" ")
try:
if len(s) == 0:
return None
elif len(s) == 1:
clean=models.Person.objects.get(first_name=s[0])
elif len(s) == 2:
clean=models.Person.object.objects.get(first_name=s[0],last_name=s[1])
elif len(s) == 3:
clean=models.Person.object.objects.get(first_name=s[0],middle_name=s[1],last_name=s[2])
else:
return None
except self.object.DoesNotExist, e:
raise ValidationError(u"Cannot find object %s: %s" % (value,e))
return clean
=== cut ===
This works fine in a normal form. The __unicode__ method is used to convert the
object into a string, and this is displayed.
If I use it in a model form however, Django will convert the database object to
the primary key value before displaying it to the widget.
This seems so wrong, as I think the widget should be called in the same manner
regardless of if it is a normal form or model form.
How do I override the fields for foreign keys?
--
Brian May <[email protected]>
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---