2012-02-21 74 views
1

型號值:Django模板:得到很多一對多的表單集

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 

booklist.html:

<table> 
{{ formset.management_form }} 
{% for form in formset.forms %} 
    <tr> 
    <td> {{ form.title.value }} </td> 
    <td> {{ form.authors }} </td> 

    </tr> 
{% endfor %} 
</table> 

所以,這個輸出多選擇每個書的作者。 如何獲取模板中作者的first_name?

感謝, 阿迪

編輯:添加意見

觀點:

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)) 

js代碼加載在thebooks頁的書單頁:

$(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; 
     }); 
    }); 

回答

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> 
+0

謝謝你的回覆,但它不工作...沒有錯誤...沒有...只是不顯示名稱 – adi 2012-02-21 13:15:25

+0

有趣的是,張貼視圖和形式的Python代碼,以便我們可以給它一試。 – jpic 2012-02-21 13:29:22

+0

我添加了視圖代碼。 實際上,「booklist」顯示在「thebooks」頁面的div中。使用js代碼。所以作者名稱的東西(模板代碼)是在書目視圖 – adi 2012-02-21 13:35:51

0

您可以在模型類使用的Unicode方法作者:

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

在下拉只需使用{{form.authors}}。而不是說作者:模型對象(或者它通常所說的任何東西),如果人名是約翰,它現在會說「約翰」。

這裏的優點當然是您也可以直接訪問選定的id。

+0

我已經定義了unicode函數......它只是格式化作者在由formset生成的多個選擇框中顯示的方式。 我的問題是我怎樣才能從模板訪問manytomany領域真正的價值觀。 – adi 2012-02-21 14:37:36