On 6/27/07, leif <[EMAIL PROTECTED]> wrote:
...
> Thanks for the input, Jeremy. I've actually decided to use newforms-
> admin since I won't be going to production for another few months

Sorry for missing that the first time.  :)

Admin uses django.newforms.models.form_for_model, which takes an
optional formfield_callback in order to map between DB fields and form
fields.

In order to supply that parameter, it looks like you'll need to
inherit from django.contrib.admin.options.ModelAdmin and override
formfield_for_dbfield.  That method maps between database fields and
form fields.

Have formfield_for_dbfield return your custom field class (a subclass
of django.newforms.fields.Field; CharField might make sense), then
override the Field.clean method to do your FK lookup and raise a
ValidationError if it's not a valid zip code.

NB: I haven't used newforms much myself yet.  Please report back if
you run into any troubles.  :)

You'll end up with something like this:

----
class MyAdmin(ModelAdmin):
   def formfield_for_dbfield(self, db_field, **kwargs):
      if isinstance(db_field, models.ForeignKey) and db_field.name ==
'zip_code':
         return ZipCodeField(**kwargs)
      else:
         super(MyAdmin, self).formfield_for_dbfield(db_field, **kwargs)

---
class ZipCodeField(CharField):
    def __init__(self, *args, **kwargs):
        self.max_length, self.min_length = 5, 5
        super(ZipCodeField, self).__init__(*args, **kwargs)

   def clean(self, value):
       value = super(ZipCodeField, self).clean(self, value)
       from yourmodels import ZipCode
       try:
          ZipCode.objects.get(pk=value)
       except ZipCode.DoesNotExist:
          raise ValidationError, "Please enter a valid zip code"
       return value

---
from django.contrib.admin import site
site.register(YourModel, YourAdminClass)

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
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
-~----------~----~----~----~------~----~------~--~---

Reply via email to