Django-默认表单字段的值

时间:2018-10-12 14:39:38

标签: django django-forms django-views

当我要通过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})

修改

这是加载时默认status字段的方式: on load

保存后,该值仍然存在,但是表单抱怨: enter image description here

使用readonly作为属性可以使该字段为只读,但仍可以对其进行编辑: enter image description here

1 个答案:

答案 0 :(得分:1)

在视图中实例化表单时,需要添加初始值。像这样

form = ArticleForm(initial={'headline': 'Initial headline'}, instance=article)

here上检查django文档的模型形式。

希望这会有所帮助!