Auto Populate field values from another model

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>

It’s not clear what you’re asking for.

Autopopulated from what?

Anyway, you can add whatever code you need in your form.is_valid block to modify SubCenter before it’s saved.

You’re already setting the centre field, you can set the other fields as well.

Autopopulate values from Centre model.

right, but that’s not working. Centre value isn’t appearing automatically.

Should we specifically mention in the html file for those 3 fields alone?

It’s still not clear to me what you want to have happen.

What values? Determined how?

What do you mean by this?

Are you talking about updating the page on the screen or the data in the model?

Please provide more details as to exactly what you want to have happen.

Sure.

The table of the model ‘Centre’ does have data of all the centres created in db.
Sub Centre is created under each Centre.

The page displays list of centres where a ‘Add’ button is placed for adding Sub Centre.
When the ‘Add’ button next to the Centre name is clicked it takes to the ‘Create_SubCentre’ form.

Now, the form needs to displays 3 fields values(of the Centre) automatically(Which I meant to be auto populating from Centre’s table data) before the user could fill in other details.

The solution which is created is not working populating/displaying those 3 fields picking values from Centre table(model) for which the SubCentre is being created.

request your help.

Ok, so you have a button for each centre in a list that is linked to SubCentre-form as shown in your unnamed template file above.

You don’t show what that URL is linked to, but since you have a view named create_SCentre shown in your views.py block above, I’ll assume that’s the view being called.

However, what I can see is that create_SCentre is expecting a parameter named pk, but your button’s url reference doesn’t supply one: {% url 'SubCentre-form' %}. (And you don’t show the url definition so I don’t know if that’s configured properly to accept a parameter.)

Thank you Ken!
But, I did follow exactly the tutorial from here ‘Formsets Tutorial
project
There, no parameter is being passed to that url as its being used as partials not as full page’s url.

possible to help me still?

What is the definition in your urls.py file for that view?

sorry.

here it is,

urlpatterns = [ 
    path('SubCentreform/', views.create_SCentre_form, name='SubCentre-form'),
    path('SubCentre/<pk>/', views.detail_SCentre, name='detail-SubCentre'),
    path('SubCentre/<pk>/update/', views.update_SCentre, name='update-SubCentre'),
    path('SubCentre/<pk>/delete/', views.delete_SCentre, name='delete-SubCentre'),
    path('<pk>/', views.create_SCentre, name='create-SubCentre'),
    
    ]

Are you not making a custom ModelForm class? when I make forms, I always create an extra script dedicated to forms where I use ModelForm.

https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/

There are lots of video tutorials on this.

You need to add a parameter to your SubCentre-form url definition, and change your {% url tag in your template to supply the appropriate value.

Thank you Ken!
that made form worked to auto populate fields.
But facing another problem… Unable to bring FK values individually for which I’d raised new thread.

Dear Spha,
Could you please elaborate a little?
Also, possible to share links to those video tutorials? - Thank you!