在這里,我正在使用模型表單并嘗試使占位符動態化。我的方法是獲取請求資料,將其傳遞給帶有 f 字串的小部件。
我想要實作的是
{'placeholder': f"commenting as {request.user.username}"}
這是我的代碼。
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ("body",)
widgets = {
"body": forms.TextInput(
attrs={
"placeholder": "Enter your comment",
"class": "comment-form-text",
}
),
}
labels = {
"body": "",
}
uj5u.com熱心網友回復:
這就是我通常在表單中傳遞request
物件的方式。
注意:您所需要的只是CommentForm.__init__
呼叫它,CommentForm(request.POST, request=request)
我剛剛添加了自定義保存,但已將其注釋掉,以表明您也可以在那里訪問它并做一些很酷的事情!:-)
表格.py
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ("body",)
widgets = {
"body": forms.TextInput(
attrs={
"class": "comment-form-text",
}
),
}
labels = {
"body": "",
}
def __init__(self, *args, **kwargs):
# # Keeping track of if it's an edit form or not ( Not Required, but handy )
# self.is_edit = True if 'instance' in kwargs else False
# Store Request Object
self.request = kwargs.pop('request') if 'request' in kwargs else None
super(CommentForm, self).__init__(*args, **kwargs)
# You can add *Any* custom attribute here to any field
self.fields['body'].widget.attrs={'placeholder': 'commenting as {0}'.format(self.request.user.username)}
# # Just showing that you can also use it in a Custom Save Method :-)
# def save(self, commit=True):
# obj = super(CommentForm, self).save(commit=False)
#
# # Note: Keeping track of **if** it's an edit so we don't re-add to the field!
# if not self.is_edit:
# # Use Request to fill a field (New)
# obj.creator = request.user
# else:
# # Use request to fill a field (edit)
# obj.last_editor = request.user
視圖.py
def commentformview(request):
form = CommentForm(data=request.POST or None, request=request)
if request.method == 'POST':
if form.is_valid():
form.save()
# redirect
data = {
'form': form,
}
return render(request, 'commentform.html', data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/519826.html
上一篇:獲取專案field_1和專案field_2重復的最新專案日期
下一篇:什么是虛擬紋理?