当我要通过UI创建模型实例时,我想默认一个字段(假设'status'为'draft'值)。我试图在` init ()中的表单中执行此操作: **型号**
class ForecastConfiguration(Control):
uuid = kp.ObjectIDField()
name = kp.ObjectNameField()
description = kp.ObjectDescriptionField()
status = models.ForeignKey(Status, blank=False, null=False, editable=True, on_delete=models.PROTECT)
表格
class ForecastConfigurationCreateForm(forms.ModelForm):
class Meta:
model = ForecastConfiguration
exclude = ['uuid', 'hierarchy_nodes']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# default status
self.fields['status'] = ModelChoiceField(queryset=ObjectStatus.get_object_status_list(self, is_form=True))
# status is defaulted when created; will get updated by planning element status
self.fields['status'].widget.attrs['disabled'] = True
这很好用:该值为默认值。但是,当我提交表单时,出现验证错误,指出该字段不能为空,并且在表单中,该值为空。
我也尝试在视图中执行此操作(结果相同):
查看
class ForecastConfigurationCreateView(CreateView):
model = ForecastConfiguration
form_class = ForecastConfigurationCreateForm
template_name = 'frontend/base/planning_create.html'
object = None
# success_url = ''
def get(self, request, *args, **kwargs):
# default status to 'Draft'
status_id = Status.objects.get(name=constant.status['draft']).uuid
form = ForecastConfigurationCreateForm(initial={'status': status_id})
member_formset = MemberFormSet()
return render(request, self.template_name, {'form': form, 'member_formset': member_formset})
修改
答案 0 :(得分:1)
在视图中实例化表单时,需要添加初始值。像这样
form = ArticleForm(initial={'headline': 'Initial headline'}, instance=article)
在here上检查django文档的模型形式。
希望这会有所帮助!