How to fetch individual FK fields

Models.py

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 '%s %s' %  (str(self.Ccode ), 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)

def create_SCentre_form(request,pk):
    centre = Centre.objects.get(pk=pk)
    form = SubCentreForms(instance=centre)
    context = {
            "form": form
        }
    return render(request, "partials/SubCentreform.html", context)

The fields from the model ‘Centre’ are autopopulated while creating data for the model ‘SubCentre’. But as shown in the below screenshot, the values are fetched together instead of individually.

FieldsFetched

How to bring the values individually?

If you take a book/publisher/author example, you can retrieve foreign key values like this:

from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()

    def __unicode__(self):
        return self.name

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

    def __unicode__(self):
        return self.title

Accessing the values through the foreign key:

b = Book.objects.get(id=1)    #(or in your case... c = Centre.objects.get(Ccode = 1) )
print(b.publisher)

print(b.publisher.website)

Accessing the data in reverse:

var = publisher.book_set.all()

or

p = Publisher.objects.all()
var = p.book_set.all()

Source:
https://django-book.readthedocs.io/en/latest/chapter10.html

Updated the following view, still unable to get the required need. Both the fields are still displaying the code value and the name value together in both the fields.

Here both the code field & centre name fields are from same model and both are modelchoice fields.
(We do need both the fields on the form) Will that be a concern? Kindly help. - thank you!

views.py

def create_SCentre_form(request,pk):
    centre = Centre.objects.get(pk=pk)
    Ccode = centre.Ccode
    zone = centre.zone
    centrename = centre.centre
    form = SubCentreForms(data={'Ccode':Ccode,'zone':zone,'centre':centrename})
    context = {
            "form": form
        }
    return render(request, "partials/SubCentreform.html", context)

We’ll need to see the form and the template to understand how and why it’s rendering that way.

Sure…

forms.py

class SubCentreForms(forms.ModelForm):

    class Meta:
        model = SubCentre

        fields = (
            'Ccode',
            'zone',
            'centre',
            'org',
            ...,
	    ...,
            ...,
	    ...,
            'remark'
            )

SubCentre_form.html which is recently modified to,

{% load crispy_forms_tags %}
<div hx-target="this" hx-swap="outerHTML">
    <form method="POST">
        <!--{% csrf_token %}
        {{ form|crispy }}-->

        <form>
            {% csrf_token %}
            <div>
                {{ form.Ccode|as_crispy_field }}
            </div>
            <div>
                {{ form.centre|as_crispy_field }}
            </div>
            <div>
                {{ form.zone|as_crispy_field }}
            </div>
            <div>
                {{ form.org|as_crispy_field }}
            </div>
	    ........
	    ........
	    ........
	    ........
            <div>
                {{ form.remark|as_crispy_field }}
            </div>
        </form>

        {% if SubCentre %}
        <br />
        <button type="submit" hx-post="{% url 'update-SubCentre' SubCentre.id %}">
            Submit
        </button>
        <button hx-get="{% url 'detail-SubCentre' SubCentre.id %}" type="button">
            Cancel
        </button>
        {% else %}
        <br />
        <button type="submit" hx-post=".">
            Submit
        </button>
        {% endif %}

    </form>
</div>

The most obvious item here is that when you have initial data to supply to the forms, you supply it using the initial attribute and not data. See The Forms API | Django documentation | Django

I don’t know how relevant that is to this specific problem, but it’s one place to start.

Also, I’d verify that the data dict has the right values in it at the time the form is instantiated.