Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a modelform's Foreignkey attribute from within a template?

Description:

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})

Question:

What is line(s) of code needed to correctly access the value: publisher.name from within template code using 'BookForm'?

like image 604
Buck Avatar asked Jul 11 '13 15:07

Buck


1 Answers

I have been able to use {{ BookForm.instance.publisher.name }} to display foreign field values. This works only to display the current instance.

like image 138
zaphod Avatar answered Nov 15 '22 06:11

zaphod