I have a simple Book Author relationship
class Author(models.Model):
first_name = models.CharField(max_length=125)
last_name = models.CharField(max_length=125)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Book(models.Model):
title = models.CharField(max_length=225)
author = models.ForeignKey(Author)
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
class BookForm(forms.ModelForm):
class Meta:
model = Book
This is what I have in my view
def addbook(request):
BookFormSet = inlineformset_factory(models.Author, models.Book, extra=1)
if request.method == 'GET':
author = models.AuthorForm()
books = BookFormSet()
else:
author = models.AuthorForm(request.POST)
if author.is_valid():
books = BookFormSet(request.POST)
if books.is_valid():
print(books)
return render_to_response('bookadd.html', locals(), context_instance = RequestContext(request))
My template looks like this
<form action="/books/add_new" method="post">
{% csrf_token %}
<table>
<tr>
<td>First name: </td>
<td>{{ author.first_name }}</td>
<td>{{author.first_name.errors}}</td>
</tr>
<tr>
<td>Last name</td>
<td>{{ author.last_name }}</td>
<td>{{author.last_name.errors}}</td>
</tr>
</table>
{{ books.management_form }}
{{ books.as_table }}
<br/>
<input type="submit" value="Submit" />
</form>
If I leave the title field blank and hit enter, on post back the book title field disappears, and I cannot figure out what to do about it. I want the field to be there with any data that was entered by the user.