Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Display a ModelForm foreign key field

Model & Form

class Book(models.Model):
  author = models.ForeignKey(User)
  name = models.CharField(max_length=50)

class BookForm(forms.ModelForm):
  class Meta:
    model = Book
    widgets = {
      'author': forms.HiddenInput(),
    }

This book form doesn't allow changing the author

Template

But I'd like to display his firstname

<form action="/books/edit" method="post">{% csrf_token %}
  {{ form.author.label }}: {{ form.author.select_related.first_name }}
  {{ form.as_p }}
</form>

Question

Of course form.author.select_related.first_name doesn't work

How can I display the firstname of the author ?

like image 795
Pierre de LESPINAY Avatar asked Apr 26 '12 11:04

Pierre de LESPINAY


People also ask

What does ForeignKey mean in Django?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.


1 Answers

This should work:

<form action="/books/edit" method="post">{% csrf_token %}
  {{ form.author.label }}: {{ form.instance.author.first_name }}
  {{ form.as_p }}
</form>

But you cannot use this form for creating books, only for updating, this won't work if the author is not set on instance.

like image 169
Ferran Avatar answered Sep 22 '22 21:09

Ferran