Dynamic form field based on another model’s entries and save them in a m2m way in Django

It’s been a while since I have done this type of brain storming stuff. Today is my country’s victory day and I have got some free time.

Objective:

I have a inventory model named Item. An item can have many attributes such as height, width etc. Think about a system where more attributes can be added in future. I wanted to build such a system where I can dynamically add these attributes so that I don’t need to modify my  model or code for this type of changes.

The idea:

The idea is very simple. I will have 3 models.

  • Item
  • Attribute
  • ItemAttribute

Item model will hold basic information about the item. In Attribute model I can add as many attribute as I wish. This model will have a type field which will determine the type of each attribute such as text, choice, number etc. It is possible to add more fields like length, required etc and add business logic for these. But for keep it simple for now.

ItemAttribute is the many to many relational table between Item and Attribute. It will have an extra field called value to store the value of this attribute.

In short: Item has many Attribute. Each of which has a value. To facilitate this we need many to many (m2m) relation between Item and Attribute.

How it is done:

Here is the gist how I achieved this functionality.

Like
Like Love Haha Wow Sad Angry

Leave a Reply

Your email address will not be published.