1

楷模:

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;
        });
    });
4

2 回答 2

1

您可以在编辑表单中访问模型实例,如下所示:

<td>
    {% if form.instance.pk %}{# if this is the form of an existing book #}
        {% for author in form.instance.authors.all %}
            {# then you can iterate over the authors of the book #}
            {{ author.first_name }}
        {% endfor %}
    {% endif %}
</td>
于 2012-02-21T12:35:51.147 回答
0

您可以在 Authors 的模型类上使用unicode方法:

class Author(models.Model):
   ...
   first_name = models.CharField(max_length=30)
   ...
   def __unicode__(self):
       return first_name

在下拉列表中只需使用 {{ form.authors }}。如果该人的名字是 John,它现在会说“John”,而不是说作者:模型对象(或通常说的任何内容)。

当然,这里的优点是您也可以直接访问选择后的 id。

于 2012-02-21T14:22:46.137 回答