Django: customized primary key based on form template

I have the following model:

UNIT = (("pounds","pounds"),("pcs","pcs"),("kg","kg"),("g","g"))

CATEGORIES = (("finished good","finished good"),("raw material","raw material"))


class Product_Hierarchy(models.Model):
    
    product_code = models.CharField(max_length=100, primary_key=True)
    parent_product_code = models.ForeignKey("self",on_delete=models.CASCADE)
    product_name = models.CharField(max_length=100)             
    product_category = models.CharField(max_length=100,choices=CATEGORIES, default="finished good")
    stock_on_hand = models.FloatField(max_length=1000000)
    unit = models.CharField(max_length=100, choices = UNIT, default="pcs")

and I am trying to set the product code to be build in accordance with the category in which the product belongs to. It does not seem possible to automatically build it after the product category selection.

Because the product creation is rendered in two templates: finished good registration template and the other one is the raw material registration template. I am wondering if I could write something that detects from where the model is accessed and automatically generate the code corresponding to the category.

Here is what my form look like:

CATEGORY_CHOICES = [
      ('finished good', 'finished good'),('raw material', 'raw material'),
]
UNIT = [("pounds","pounds"),("pcs","pcs"),("kg","kg"),("g","g")]

           
class UpdateProductForm(forms.ModelForm):
      product_category = forms.CharField(widget=forms.Select(choices=CATEGORY_CHOICES), label='Category')
      product_name = forms.CharField(label = 'Product Name')
      stock_on_hand = forms.CharField(label = 'Stock On Hand')
      unit = forms.CharField(widget=forms.Select(choices=UNIT), label='Unit')

      class Meta:
            model = Product_Hierarchy
            fields = ("product_name", "product_category", "stock_on_hand", "unit")

I have not yet found a way to do that, the documentation does not cover it and my skills are not even close to let me build it from scratch. Would someone as a clue on how to do it or where to look?

Back to Top