2012-06-23 102 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