简体   繁体   中英

How to access a foreign key related field in a template when using Django model form

My Objective

Access the field name in the Parent Model ParentModel and display its content in a form instance in the template. For example, let the field parent be a foreign key in the ChildModel as described below.

What I have tried

Access the parent field in the form as {{ form.parent.name }} in the template

Errors received

Tried looking up form.parent.name in context

models.py

class ParentModel(models.Model):
    name = models.CharField()
    
    def __str__(self):
        return self.name

class ChildModel(models.Model):
    parent = models.ForeignKey(ParentModel)
    
    def __str__(self):
        return self.parent.name

forms.py

class ChildModelForm(ModelForm):
    class Meta:
        model = ChildModel
        fields = '__all__'
        widgets = {'parent': forms.Select(),}

views.py

def childView(request, pk):
    template = 'template.html'
    child = ChildModel.objects.get(parent=pk)
    form = ChildModelForm(instance=child)
    if request.method == 'POST':
        form = ChildModelForm(request.POST, instance=child)
        if form.is_valid():
            form.save()
        else:
            form = ChildModelForm(instance=child)
    context = {'form': form, }
    return render(request, template, context)

template.html

<form method="POST" action="">
   {% csrf_token %}
   {{form.parent.name}}
   <button type="submit">Save</button>
</form>

Now the child model form displays pk I want to display the name of the parent field

I have also tried using this Django access foreignkey fields in a form but it did not work for me.

From my understanding, you want to display the form instance's values. You can do:

form.instance.parent.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM