I have 2 tables/models, which for all practical purposes are the same as the standard Author/Book example, but with the additional restriction that in my application each Author can only write 0 or 1 books. (eg, the ForeignKey field in the Book model is or can be a OneToOneField, and there may be authors who have no corresponding book in the Book table.)
I would like to be able to display a form showing multiple books and also show some fields from the corresponding Author table (eg author_name, author_address). I followed the example of the inlineformset and but that doesn't even display the author name in the generated form.
EDIT --- Added code sample
# Models
class Author(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
class Book(models.Model):
author = models.OneToOneField(Author)
title = models.CharField(max_length=100)
# views
def manage_books(request):
author = Author.objects.get(pk=1)
BookInlineFormSet = inlineformset_factory(Author, Book)
formset = BookInlineFormSet(instance=author)
return render_to_response("manage_books.html", {
"formset": formset,
})
# template
<table>
<tr>
<th>Author</th>
<th>Address</th>
<th>Title</th>
</tr>
{% for form in formset.forms %}
<tr>
<td>{{ form.author }}</td>
<td>{{ form.author_address }}</td>
<td>{{ form.title }}</td>
</tr>
{% endfor %}
</table>
The output is blank for the Author and the Author_address Note I can get the author to print if I define a unicode function in the model, but that doesn't solve the general problem. Note also that form.author.address doesn't work either.