Frederik Voordeckers
Frederik Voordeckers

Reputation: 1331

Django repeatable field with only new items

I want to create an Instruction that has multiple Steps. A simplified model would look like this:

class Step(models.Model):
    description = models.CharField(max_length=255)

class Instruction(models.Model):
    steps = models.ForeignKey(Step)

The problem is that I want to create a new Instruction with multiple steps, but when I create one in the admin, I should have a repeatable form field. For each step I can add a field and create a new Step. I do not need to be able to select an already existing step. I'm not sure if there is something OOTB of a package that already does that... Any ideas how to tackle this?

To give an example of what I'm trying to accomplish: the ACF repeater field in WP: enter image description here

In my case I would only need a description field with the description of the step

Upvotes: 3

Views: 1522

Answers (1)

rnevius
rnevius

Reputation: 27092

You have things a bit backwards. The ForeignKey relationship should be the other way around (since an instruction can have many steps, but each step only has one related instruction...a Many-to-One relationship).

class Step(models.Model):
    description = models.CharField(max_length=255)
    instruction = models.ForeignKey(Instruction, related_name='steps')

class Instruction(models.Model):
    # some fields

Now, in your Admin, you can use inlines to display these fields in a "repeatable" manner, similar to ACF.

Upvotes: 2

Related Questions