Brand new to Django
using django 4.2 python 3.11
I have 5 models in all. For simplicity consider default id and name as their fields. Models are Company, Customer, Site, department and equipment.
from django.db import models
class Company(models.Model):
name = models.CharField(max_length=100)
class Customer(models.Model):
name = models.CharField(max_length=100)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
class Site(models.Model):
name = models.CharField(max_length=100)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
class Department(models.Model):
name = models.CharField(max_length=100)
site = models.ForeignKey(Site, on_delete=models.CASCADE)
class Equipment(models.Model):
name = models.CharField(max_length=100)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
They connect each other via just one foreign key.
In create view of equipment via model form, I want to first select the company then based on company the customer and then based on customer, select site and then department based on site. But with only one foreignkey from equipment to department, only one field loads via complete form render.
I do not want to create multiple foreign keys from equipment to all other models. I would use django-select2 for dependent dropdowns.
I used select2 ModelSelect2Widget fields to create site and Customer dropdowns with search enabled using
class CreateEquipmentForm(ModelForms):
site = forms.ModelChoiceField(
queryset=Site.objects.all(),
label="Select Site",
widget=ModelSelect2Widget(
search_fields=['site_name__icontains'],
dependent_fields={'customer': 'customer'},
)
)
## rest all as per django
This gets the fields populated, but they are not saved to the database.
Tried using htmx, but cannot save to db. I tried using django-select 2
What I am expecting?
Want to be able to select all model fields from different models stated above when creating the equipment.
So on equipment form I would like to first select the company then customer and finally enter equipment name.
How do I save all fields to db.