How could we achieve auto-populating fields values as soon as a field value is given?
There are 2 models, Centre & SubCentre
Need 2 fields values from Centre to be auto-populated while creating SubCentre.
As soon as the Add button is clicked, the loading form should have the Centre, Zone & CCode value to be autopopulated.
Request help in correcting the codes below. - Thank you!
Models:
class Centre(models.Model):
Ccode = models.AutoField(primary_key=True)
zone = models.CharField(max_length=4, blank=True, null=True)
centre = models.CharField(max_length=50, unique=True, blank=True, null=True)
def __str__(self):
return self.centre
class SubCentre(models.Model):
Ccode = models.ForeignKey(Centre, blank=True, null=True, on_delete=models.SET_NULL, to_field="Ccode", related_name="Ccode")
zone = models.CharField(max_length=4, blank=True, null=True)
centre = models.ForeignKey(Centre, blank=True, null=True, on_delete=models.SET_NULL, to_field="centre", related_name="centre")
org = models.ForeignKey(org, blank=True, null=True, on_delete=models.SET_NULL, to_field="Org", db_column="org")
name = models.CharField(max_length=50, blank=True, null=True)
def __str__(self):
return str(self.name)
Views.py
def create_SCentre(request,pk):
centre = Centre.objects.get(pk=pk)
SubCentres = SubCentre.objects.filter(centre=centre)
#initial_dict = {'Ccode':centre.Ccode, 'zone':centre.zone, 'centre':centre.centre}
form = SubCentreForms(request.POST or None, instance=centre)
if request.method == "POST":
if form.is_valid():
SubCentre = form.save(commit=False)
SubCentre.centre = centre.centre
SubCentre.save()
return redirect('detail-SubCentre', pk=SubCentre.id)
else:
return render(request, 'partials/SubCentre_form.html', {
"form": form
})
context = {
"form": form,
"centre": centre,
"SubCentres": SubCentres
}
return render(request, 'create_SubCentre.html', context)
html
<div>
<h2 >
Create Sub Centre for {{ centre.centre }}
</h2>
</div>
<div class="mt-4 flex md:mt-0 md:ml-4">
<button hx-get="{% url 'SubCentre-form' %}" hx-swap="beforeend" hx-target="#forms">
Add Sub Centre
</button>
</div>
<div id="forms" class="py-5 mt-5"></div>