楷模:
class Author(models.Model):
...
first_name = models.CharField(max_length=30)
...
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
...
形式:
class BookForm(ModelForm):
class Meta:
model = Book
书单.html:
<table>
{{ formset.management_form }}
{% for form in formset.forms %}
<tr>
<td> {{ form.title.value }} </td>
<td> {{ form.authors }} </td>
</tr>
{% endfor %}
</table>
因此,这将为每本书的作者输出一个多选框。如何获取模板中作者的名字?
谢谢,阿迪
编辑:添加视图
意见:
def thebooks(request):
BookFormSet = modelformset_factory(Book, form = BookForm)
if request.method == 'POST':
formset = BookFormSet(request.POST)
if formset.is_valid():
formset.save()
else:
formset = BookFormSet(queryset = Book.objects.all())
return render_to_response('thebooks.html', {'formset': formset,}, context_instance=RequestContext(request) )
def booklist(request):
BookFormSet = modelformset_factory(Book, form = BookForm)
formset = BookFormSet(request.POST)
return render_to_response('booklist.html', {'formset':formset,}, context_instance=RequestContext(request) )
在 thebooks 页面加载 booklist 页面的 js 代码:
$(document).ready(function() {
$("#form").submit(function() {
$.post('/books/booklist/', $(this).serialize(),
function(data) {
if (data == "") { alert("No data returned!"); return; }
// otherwise set the content div to the data we received
$('#allElements').html(data);
}
);
// disable normal submitting of the form since we use ajax now
return false;
});
});