在閱讀 Django 的檔案的同時,我也在嘗試練習。今天我正在閱讀 Formsets;https://docs.djangoproject.com/en/4.0/topics/forms/formsets/
現在我試圖用初始資料填充通用 FormView。這是代碼:
class ArticleFormView(FormView):
# same here, use FormSet instance, not standard Form
form_class = ArticleFormSet
template_name = 'article_form_view.html'
success_url = "/"
def get_initial(self):
init_data = {'value1': 'foo', 'value2': 'bar'}
return init_data
這導致“in _construct_form defaults['initial'] = self.initial[i] KeyError
: 0”
所以問題是如何使用初始資料在 FormView 中填充表單集?
uj5u.com熱心網友回復:
您需要將初始資料作為串列傳遞,其中第i個元素是第i個表單的初始資料。因此,如果您只想傳遞第一個表單的初始資料,請將其傳遞為:
class ArticleFormView(FormView):
form_class = ArticleFormSet
template_name = 'article_form_view.html'
success_url = "/"
def get_initial(self):
return [{'value1': 'foo', 'value2': 'bar'}] # ?? list of dictionaries
如果要將其作為所有表單的初始資料傳遞,可以使用form_kwargs引數:
class ArticleFormView(FormView):
form_class = ArticleFormSet
template_name = 'article_form_view.html'
success_url = "/"
def get_form_kwargs(self):
data = super().get_form_kwargs()
data['form_kwargs'] = {'initial': {'value1': 'foo', 'value2': 'bar'}} # ?? initial for all forms
return data
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/400911.html
