'How to write a Django model form to include selected fields from multiple tables
There are many questions about building model forms from multiple tables, but I couldn't find a solution to my problem.
Background: In model.py I have 3 simple models with 1-many relationship
class site(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
sitename = models.CharField(max_length=150)
site_address = models.CharField(verbose_name='Address', max_length=200, null=True, blank=True)
class block(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
blockname = models.CharField(max_length=150)
sitename = models.ForeignKey(site, on_delete=models.CASCADE, )
class quarter(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
quartername = models.CharField(max_length=150)
blockname = models.ForeignKey(block, on_delete=models.CASCADE, )
I have separate forms for each model - where user can add, edit and delete and site, block using standard djando modelform and modelformset.
The challenge I'm facing is with creating a quarter form. On a quarter from I want user to select a site from drop-down, which will populate block and then use can enter quarter name and save submit.
Now, 1 possible solution is to include site as FK in quarter and that will solve the problem - but I don't want to do that. I even tried create separate form instances and call it in view and template - but the problem with this solution is that the mandatory field name from site are also displayed.
How can I show the sitename dropdown on quarter form - where on selecting sitename the user is shown corresponding blockname. On click of save button the data for quarter is saved in db (don't have to save site or block data because we already have those entries)
Any suggestion on approach or solution?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
