1

In formsets.py, you find this code snippet

class BaseFormSet(StrAndUnicode):
    """
    A collection of instances of the same Form class.
    """
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList):
        ...
        self.prefix = prefix or self.get_default_prefix()   # Note the self.get_default_prefix
        ...
    ...
    @classmethod                                            # Note the @classmethod
    def get_default_prefix(cls):
        return 'form'

Why is get_default_prefix declared this way and then called with self.? Is there something gained by doing it this way? get_default_prefix has another definition in BaseInlineFormSet (forms/models.py)

class BaseInlineFormSet(BaseModelFormSet):
    ...
    @classmethod
    def get_default_prefix(cls):
        from django.db.models.fields.related import RelatedObject
        return RelatedObject(cls.fk.rel.to, cls.model, cls.fk).get_accessor_name().replace('+','')

and another in BaseGenericInlineFormset again using the @classmethod, so it doesn't appear to be a typo. I just don't understand why it would be done this way and then called with self.

The only clue I see (which I don't understand) is that the admin seems to call it with FormSet.get_default_prefix()

I'm wondering if there is something I'm just not understanding about python.

boatcoder
  • 17,525
  • 18
  • 114
  • 178

1 Answers1

1

Calling a class method from an instance is perfectly legal, as you can see in the code. A related stackoverflow post said there was no benefit, (and it is bad practice) to call from an instance; because if you are only calling from instance your method should probably not be a classmethod.

I think you answer your own question, though. If django is calling FormSet.get_default_prefix() from somewhere, then they probably didn't want to instantiate a formset object

Community
  • 1
  • 1
dm03514
  • 54,664
  • 18
  • 108
  • 145