我研究這一點,許多答案在那裏觸摸它(表單集,前綴等),但沒有正是我後...多評論形式 - Django的
我有一個應用程序,允許用戶將卡片發佈到電路板,每張卡片可以有零個或多個評論。我建立了數據庫關係,所以如果手動添加板卡,卡片或註釋對象,我可以在模板中顯示它們。
卡的形式也工作,所以這不是一個問題。但是現在我想用click
事件(我正在使用jQuery)顯示textarea
的評論。問題是,表單不顯示該字段。下面是表單代碼:
class AddCommentForm(ModelForm):
class Meta:
model = Comment
fields = ['message']
message = forms.CharField(
widget=forms.Textarea(
attrs={
'class': 'form-control comment-input'
'name': 'message',
'placeholder': 'Comment away...'
}
),
required=False,
)
馬上蝙蝠,存在這樣一個問題,當Django的呈現形式,它使用id
。在這種情況下,它最終是id_message
或message
(取決於我是否在表單類中指定)。當然,在HTML中,這並不好。我在shell中證實了這一點:
>>> import django; import project
>>> from apps.board.forms import AddCommentForm
>>> comment_form = AddCommentForm(); print(comment_form)
<tr><th><label for="message">Message:</label></th><td><textarea class="form-control comment-input" cols="40" id="message" name="message" placeholder="Comment away..." rows="10">
</textarea></td></tr>
所以我想用formsets
的,但似乎不太對勁,因爲我理解他們,他們是一個form
標籤內的幾種形式。我的情況不同,因爲每張卡都有零個或多個註釋,並且HTML的流程表明應該有幾個form
元素。
另一個挑戰是我需要兩個視圖:一個處理卡片,一個處理每個評論。我目前正在使用不同的動作值來實現這一點,它似乎工作。
看起來我的用例並不奇怪,我可以想到這種情況會發生的幾種情況:Twitter回覆,博客文章評論等。我只是不能讓Django與這個。
我也應該注意到,我可以手動與這本作品:
<label>
<textarea class="form-control comment-input" name="message"></textarea>
<button type="submit"></button>
</label>
UPDATE
這裏是一個視圖段:
class AddCommentView(View):
model = Comment
form_class = AddCommentForm
template_name = 'somedir/template.html'
@method_decorator(login_required)
def get(self, request):
comment_form = self.form_class()
return render(request, self.template_name, {
'comment_form': comment_form
})
如果窗體工作(從上面的代碼片段和shell測試),我希望這會顯示在頁面上。
URL配置是在這裏:
url(r'^comment/add/$', AddCommentView.as_view(), name='add_comment_view'),
在寫這個的時候,我看到一個混亂一片。我的視圖網址是/comment/add/
,但我希望表單的顯示位置爲/dashboard/
。問題是,該網址上還有另一個視圖。
如果我建立沒有Django表單的表單,然後發佈數據到/comment/add/
評論被創建並保存在數據庫中。所以我想我仍然在試圖弄清楚如何在一個模板中使用多個表單來使用兩個視圖。 @丹尼爾羅斯曼指出使用prefix
,我想這值得探索更多。
更新2
所以我就用這個前綴通過刪除該視圖的URL和意見結合到一個視圖中工作。兩種形式,一種觀點,一種模板。但...
該來源仍顯示重複id
s。我最終沒有把id
放在窗體屬性列表中。由於這是無效的HTML,什麼是最好的方法來解決這個問題?
筆者認爲:
card_model = Card
comment_model = Comment
card_form_class = AddCardForm
comment_form_class = AddCommentForm
. . .
@method_decorator(login_required)
def get(self, request):
card_form = self.card_form_class(prefix='card')
comment_form = self.comment_form_class(prefix='comment')
. . .
更新3
我已經找到了解決這一問題。爲了實例的形式,你需要添加auto_id=False
防止多重,複製id
S:
comment_form = self.comment_form_class(prefix='comment', auto_id=False)
我很困惑,你說表單沒有被渲染,然後你說它使用'id_message'來渲染它。這是什麼?另外,你有什麼問題,它有一個id_message id? – onyeka
恩,夫妻倆......我沒有說它是用那個'id'呈現的。我說結果是......我知道Django做了什麼,因爲我在其他地方使用了它的形式。其次,我在shell中進行了測試,證實了這一點。爲了清楚起見,我將添加這個問題。 'id's的問題是,在HTML中你只能有一個'id',所以表單會在多個'form's中以相同的'id'呈現。 – nicorellius
讓我們看看你的看法。 – onyeka