Django form sets the default initial value

created at 07-15-2021 views: 2

Introduction

Use django, use form in django to format data, individual fields will have a default value, use initial to set the default value, but after form.is_valid, it is found that the field does not have a default value.

reason

In django, initial is not equal to the default value, related links: here

  1. The initial value of the field is intended to be displayed in HTML. However, if the user deletes the value and eventually sends back a blank value for this field, the initial value will be lost. Therefore, you cannot get the results expected by the default behavior.
  2. The default behavior is: if the value validation process will take the data statement does not contain any value of the field

Solution

initial={"":""}
form=ArticleModel(request.POST)
if form.has_changed():
    data = {i: form.cleaned_data[i] for i in form.changed_data}
    data.update({key: val for key, val in init_praram.items() if key not in form.changed_data})
Please log in to leave a comment.