我有简单的图书作者关系。
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
这是我的看法。
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))
我的模板希望这样做。
<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>
如果我离开标题领域空白,打上栏,书标题领域消失了,我无法说明这方面的情况。 我希望现场有用户输入的任何数据。