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
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>
Of course form.author.select_related.first_name
doesn't work
How can I display the firstname of the author ?
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.
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.
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