I would like to know how to access a ForeignKey's field within template code.
Given the sample models.py code:
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
class Book(models.Model):
title = models.CharField(max_length=100)
publisher = models.ForeignKey(Publisher)
And Sample forms.py code:
class BookForm(ModelForm):
class Meta:
model = Book
fields = ['title', 'publisher']
And sample views.py code:
def sample(request):
bf = BookForm(request.POST)
return render(request, 'sample.html', {'BookForm': bf})
What is line(s) of code needed to correctly access the value: publisher.name from within template code using 'BookForm'?
I have been able to use {{ BookForm.instance.publisher.name }}
to display foreign field values. This works only to display the current instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With