DevKing
DevKing

Reputation: 231

Django - Defaulting a Form Field's Value

When I am about to create a model instance via the UI, I'd like to default a field (let's say 'status' to value 'draft'). I tried to do this in the Form in `init(): ** Model**

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)

Form

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

This works fine: the value is defaulted. However, when I submit the form I get a validation error saying that this field cannot be empty and in the form, the value is empty.

I tried doing this in the view as well (same result):

View

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})

Edit

This is how the status field is defaulted when loading: on load

After saving, the value is still there but the form complains: enter image description here

Using readonly as the attribute makes the field read-only but it still can be edited: enter image description here

Upvotes: 0

Views: 665

Answers (1)

devdob
devdob

Reputation: 1504

You need to add your initial values when you instantiate your form in the view. Something like so,

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

Check the django docs for model forms right here.

Hope this helps!

Upvotes: 1

Related Questions