2012-06-23 39 views
0

我已經添加了inline_formset。但是{{ form.name }}它沒有在模板中顯示。我錯過了什麼嗎?感謝inline_formset缺少字段

class Album(models.Model): 
    name = models.CharField(('album name'), max_length=100) 
    owner = models.ForeignKey(User, verbose_name=('user'), related_name=('users')) 

class Song(models.Model): 
    album = models.ForeignKey(Album, verbose_name=('album'), related_name=('songs')) 
    title = models.CharField(('song name'), max_length=100) 
    artist = models.CharField(('artist name'), max_length=100) 

inline_formset

AlbumFormSet = inlineformset_factory(Album, Song) 

模板

<tr> 
     <td>{{ form.name }}</td> <-- its not showing 
     <td>{{ form.title }} </td> 
     <td>{{ form.artist }} </td> 
    </tr> 
{% endfor %} 

{{ formset.management_form }} 

UPDATE

    {% for form in formset %} 
        <tr> 

         <td>{{ form.title }} </td> 
         <td>{{ form.artist }} </td> 
         <td>{{album_form.name}}</td> 
         <td>{{ form.errors }}</td> 
        </tr> 
       {% endfor %} 

我添加了單獨的ModelForm的專輯,然後for循環中添加的。 NOw重複輸入標籤名稱。 <input id="id_name" type="text" name="name" maxlength="100">

最新

我已經添加了以下數據。數據被保存。但是有一個奇怪的問題。只有Last Album不保存爲Test 1Test 2

enter image description here

enter image description here enter image description here

enter image description here

回答

1

我認爲inlineformset不包括專輯模型的表單。你必須爲Album創建一個單獨的ModelForm,然後執行諸如{{album_form.name}}之類的操作。

您可以查看 - 你用ForeignKey的這張專輯表單集關聯你在像這樣的東西

# validation and other code 
# --------------------------- 
new_album = Album() 
new_album_form = AlbumModelForm(request.POST,instance=new_album) 
song_formset = AlbumFormset(request.POST) 
new_album_form.save() 
songs = song_formset.save(comit=False) 
for song in songs: 
    song.album = new_album 
    song.save() 

編輯:

,如果你想創建一個相冊上述解決方案可能工作和多張帶有外鍵的歌曲。爲了得到你想要的東西,即{{form.name}},{{form.title}}{{form.artist}}使用標準的formset,名稱,標題和藝術家字段,而不是modelformset。

+0

我認爲你是對的。如果我爲專輯創建單獨的模型表單。那我怎麼把他們的數據聯繫起來呢?因爲我已將外鍵應用於「專輯」。我如何保存數據? – Kulbir

+0

好的我已經爲Album添加了單獨的ModelForm。然後''{album_form.name}}'''formset' forloop。但是它的重複輸入標籤名稱爲:<'。我如何擺脫這個問題? – Kulbir

+0

我已經用樣本snipest更新了ans。我認爲它可能工作。 – machaku

0

沒有在形式的name字段。該表單用於歌曲,並且它們有album,titleartist

+0

我也試過'form.album'。但沒有運氣。 – Kulbir