Thanks Tim. Something like that would work, perhaps the first step
would be to make modelfield.formfield a bit more configurable ?

Currently, the default form field class for a model field is hardcoded
in the model field's formfield() method, ie:
https://github.com/django/django/blob/master/django/db/models/fields/related.py#L945

Changing this to an attribute allows to replace it in an
AppConfig.ready() method as such:

    class TestApp(AppConfig):
        name = 'select2_one_to_one'

        def ready(self):
            model = self.get_model('TestModel')
            # Perhaps that's the kind of nice place to override this
kind of things
            model._meta.get_field('test').formfield_defaults['widget']
= forms.RadioSelect
            # django-autocomplete-light users would execute something like:
            model._meta.get_field('test').formfield_defaults['widget']
= autocomplete.Select2(url='my_autocomplete_url')

This also allows to change it when defining the field:

    class TestModel(models.Model):
        name = models.CharField(max_length=200)

        test = models.OneToOneField(
            'self',
            null=True,
            blank=True,
            related_name='related_test_models',
            # This seems like it would always be useful
            formfield_defaults={
                'widget': forms.RadioSelect
            }
        )

I checked that this changed rendering in the admin, and it felt pretty
awesome I recon, to see my override in the default form and inline
model forms too.

Here's what the poc patch looks like for ForeignKey (3 additions and 1
deletion, works on OneToOne field too):

https://github.com/jpic/django/commit/d102f362f3c1ceaf2d5224d71f788c0821a481ae

Of course, that works when the model field already supports a form
field. It doesn't solve the problem with virtual fields that don't
have a formfield() method like GenericForeignKey, where an app would
like to be able to provide a formfield() as well as logic for
modelfield.{value_from_object,save_form_data}(). Perhaps that's
something we could deal with later *if* we decide to deal with it ?

Meanwhile, could we perhaps start working on a consistent way to
configure formfield() in Django ? That doesn't solve all the use cases
I mentioned, but perhaps it would be a nice step forward.

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/CALC3KaeBNZwpwrY0QRisKNGdD98_0iJV2%3DNrH5Nzkd-892Xakw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to