Django override-able abstract field for inlineformset

179 Views Asked by At

Intro

Hello!!!!! I've looked for the solution to this problem already - the nearest thing I've found so far is this, and it doesn't have a full enough answer for me.

Background

The following is a contrived example to make my question clearer.

I am interested in using inlineformset_factory in a situation where each entry in the form can correspond to different subclasses of the same parent model. For example, say I have a form model that has a number of input items:

class Form(models.Model):
    name = models.CharField(max_length=30)

Then, I have an Input model and its subclasses:

class Input(models.Model):
    class Meta:
        abstract = True

    form = models.ForeignKey(Form)
    name = models.CharField(max_length=30)

class ShortInput(Input):
    value = models.CharField(max_length=20)

class TweetInput(Input):
    value = models.CharField(max_length=140)

class BinaryInput(Input):
    value = models.TextField(blank=True)

Essentially, it's a form with various types of data. It's important that ShortInput instances only take up 20 characters of space in the backend, and BinaryInput instances have a huge amount of storage space. Note also that every subclass of Input will always have a value field, although they may be of different lengths/types.

What I'd like to do now is use inlineformset_factory to build the Form model. Looks like this:

form = inlineformset_factory(
    Form,
    Input,
    fk_name='form',
    fields=['value']
)

The intention here is to build a form where I can edit the values of every Input entry in the database.

The problem

For the inlineformset_factory call, Django complains that Input has no field named value.

The question

I feel I should be able to deal with this problem because I can guarantee every Input subclass will have a value attribute - I just need to tell this to Django in some way. The ideal thing I'm looking for is something like this:

class Input(models.Model):
    class Meta:
        abstract = True
        guaranteed_subclass_fields = [
            'value',
        ]
    ...

In other words, a way of telling Django it can expect a value field in subclasses.

The next best thing I'm looking for is some other way of specifying to Django that it can rely on a value field existing.

Finally, if none of this is possible, I'm looking for some other (potentially hackish) way of passing my Input class with a value field to the inlineformset_factory function - perhaps ignoring the error or something of the sort. (Although regardless of how hackish the solution is, I would like it to involve the use of inlineformset_factory)

Thanks in advance for any help!

0

There are 0 best solutions below